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
`clientOptions` also includes headers that should be added to all the requests. https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java#L162
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; policies.add(new UserAgentPolicy(buildLogOptions.getApplicationId(), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(buildLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); }
.clientOptions(clientOptions)
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions = new ClientOptions(); private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object * * @throws NullPointerException If {@code clientOptions} is {@code null}. */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
Why does calling `setConfigurationSetting` throw RuntimeException?
public void clientOptionsIsPreferredOverLogOptions() { ConfigurationClient configurationClient = new ConfigurationClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) .httpClient(httpRequest -> { assertTrue(httpRequest.getHeaders().getValue("User-Agent").contains("aNewApplication")); return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); }) .buildClient(); assertThrows(RuntimeException.class, () -> configurationClient.setConfigurationSetting(key, null, value)); }
assertThrows(RuntimeException.class, () -> configurationClient.setConfigurationSetting(key, null, value));
public void clientOptionsIsPreferredOverLogOptions() { ConfigurationClient configurationClient = new ConfigurationClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) .httpClient(httpRequest -> { assertTrue(httpRequest.getHeaders().getValue("User-Agent").contains("aNewApplication")); return Mono.just(new MockHttpResponse(httpRequest, 400)); }) .buildClient(); assertThrows(HttpResponseException.class, () -> configurationClient.setConfigurationSetting(key, null, value)); }
class ConfigurationClientBuilderTest extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String DEFAULT_DOMAIN_NAME = ".azconfig.io"; private static final String NAMESPACE_NAME = "dummyNamespaceName"; private final String key = "newKey"; private final String value = "newValue"; private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString(); static String connectionString = "Endpoint=http: @Test public void missingEndpoint() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.buildAsyncClient(); }); } @Test public void malformedURLExceptionForEndpoint() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.endpoint("htp: }); } @Test public void nullConnectionString() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString(null).buildAsyncClient(); }); } @Test public void emptyConnectionString() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("").buildAsyncClient(); }); } @Test public void missingSecretKey() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa;Secret=").buildAsyncClient(); }); } @Test public void missingId() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=;Secret=aaa").buildAsyncClient(); }); } @Test public void invalidConnectionStringSegmentCount() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa").buildAsyncClient(); }); } @Test public void nullAADCredential() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.endpoint(ENDPOINT).credential(null).buildAsyncClient(); }); } @Test public void timeoutPolicy() { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); final ConfigurationClient client = new ConfigurationClientBuilder() .connectionString(connectionString) .addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient(); assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void nullServiceVersion(HttpClient httpClient) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set."); final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder() .connectionString(connectionString) .retryPolicy(new RetryPolicy()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(null) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient); if (!interceptorManager.isPlaybackMode()) { clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value); assertEquals(addedSetting.getKey(), key); assertEquals(addedSetting.getValue(), value); } @Test public void defaultPipeline() { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set."); final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder() .connectionString(connectionString) .retryPolicy(new RetryPolicy()) .configuration(Configuration.getGlobalConfiguration()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .pipeline(new HttpPipelineBuilder().build()); if (!interceptorManager.isPlaybackMode()) { clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); assertThrows(HttpResponseException.class, () -> clientBuilder.buildClient().setConfigurationSetting(key, null, value)); } HttpClient defaultHttpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : new NettyAsyncHttpClientBuilder().wiretap(true).build(); clientBuilder.pipeline(null).httpClient(defaultHttpClient); ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value); assertEquals(addedSetting.getKey(), key); assertEquals(addedSetting.getValue(), value); } @Test @Test public void clientOptionHeadersAreAddedLast() { ConfigurationClient configurationClient = new ConfigurationClientBuilder() .connectionString(connectionString) .clientOptions(new ClientOptions() .setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) .httpClient(httpRequest -> { assertEquals("custom", httpRequest.getHeaders().getValue("User-Agent")); return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); }) .buildClient(); assertThrows(RuntimeException.class, () -> configurationClient.setConfigurationSetting(key, null, value)); } private static URI getURI(String endpointFormat, String namespace, String domainName) { try { return new URI(String.format(Locale.US, endpointFormat, namespace, domainName)); } catch (URISyntaxException exception) { throw new IllegalArgumentException(String.format(Locale.US, "Invalid namespace name: %s", namespace), exception); } } }
class ConfigurationClientBuilderTest extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String DEFAULT_DOMAIN_NAME = ".azconfig.io"; private static final String NAMESPACE_NAME = "dummyNamespaceName"; private final String key = "newKey"; private final String value = "newValue"; private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString(); static String connectionString = "Endpoint=http: @Test @DoNotRecord public void missingEndpoint() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.buildAsyncClient(); }); } @Test @DoNotRecord public void malformedURLExceptionForEndpoint() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.endpoint("htp: }); } @Test @DoNotRecord public void nullConnectionString() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString(null).buildAsyncClient(); }); } @Test @DoNotRecord public void emptyConnectionString() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("").buildAsyncClient(); }); } @Test @DoNotRecord public void missingSecretKey() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa;Secret=").buildAsyncClient(); }); } @Test @DoNotRecord public void missingId() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=;Secret=aaa").buildAsyncClient(); }); } @Test @DoNotRecord public void invalidConnectionStringSegmentCount() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa").buildAsyncClient(); }); } @Test @DoNotRecord public void nullAADCredential() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.endpoint(ENDPOINT).credential(null).buildAsyncClient(); }); } @Test @DoNotRecord public void timeoutPolicy() { final ConfigurationClient client = new ConfigurationClientBuilder() .connectionString(connectionString) .addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient(); assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void nullServiceVersion(HttpClient httpClient) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set."); final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder() .connectionString(connectionString) .retryPolicy(new RetryPolicy()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(null) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient); if (!interceptorManager.isPlaybackMode()) { clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value); assertEquals(addedSetting.getKey(), key); assertEquals(addedSetting.getValue(), value); } @Test public void defaultPipeline() { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set."); final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder() .connectionString(connectionString) .retryPolicy(new RetryPolicy()) .configuration(Configuration.getGlobalConfiguration()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .pipeline(new HttpPipelineBuilder().build()); if (!interceptorManager.isPlaybackMode()) { clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); assertThrows(HttpResponseException.class, () -> clientBuilder.buildClient().setConfigurationSetting(key, null, value)); } HttpClient defaultHttpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : new NettyAsyncHttpClientBuilder().wiretap(true).build(); clientBuilder.pipeline(null).httpClient(defaultHttpClient); ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value); assertEquals(addedSetting.getKey(), key); assertEquals(addedSetting.getValue(), value); } @Test @DoNotRecord @Test @DoNotRecord public void clientOptionHeadersAreAddedLast() { ConfigurationClient configurationClient = new ConfigurationClientBuilder() .connectionString(connectionString) .clientOptions(new ClientOptions() .setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) .httpClient(httpRequest -> { assertEquals("custom", httpRequest.getHeaders().getValue("User-Agent")); return Mono.just(new MockHttpResponse(httpRequest, 400)); }) .buildClient(); assertThrows(HttpResponseException.class, () -> configurationClient.setConfigurationSetting(key, null, value)); } private static URI getURI(String endpointFormat, String namespace, String domainName) { try { return new URI(String.format(Locale.US, endpointFormat, namespace, domainName)); } catch (URISyntaxException exception) { throw new IllegalArgumentException(String.format(Locale.US, "Invalid namespace name: %s", namespace), exception); } } }
Should the `HttpPipelineBuilder` handle this?
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; policies.add(new UserAgentPolicy(buildLogOptions.getApplicationId(), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(buildLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); }
.clientOptions(clientOptions)
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions = new ClientOptions(); private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object * * @throws NullPointerException If {@code clientOptions} is {@code null}. */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
will remove .clientOptions(clientOptions) and follow the pattern used in KV
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; policies.add(new UserAgentPolicy(buildLogOptions.getApplicationId(), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(buildLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); }
.clientOptions(clientOptions)
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions = new ClientOptions(); private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object * * @throws NullPointerException If {@code clientOptions} is {@code null}. */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
Updated with verfiy HttpResponseException
public void clientOptionsIsPreferredOverLogOptions() { ConfigurationClient configurationClient = new ConfigurationClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) .httpClient(httpRequest -> { assertTrue(httpRequest.getHeaders().getValue("User-Agent").contains("aNewApplication")); return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); }) .buildClient(); assertThrows(RuntimeException.class, () -> configurationClient.setConfigurationSetting(key, null, value)); }
assertThrows(RuntimeException.class, () -> configurationClient.setConfigurationSetting(key, null, value));
public void clientOptionsIsPreferredOverLogOptions() { ConfigurationClient configurationClient = new ConfigurationClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) .httpClient(httpRequest -> { assertTrue(httpRequest.getHeaders().getValue("User-Agent").contains("aNewApplication")); return Mono.just(new MockHttpResponse(httpRequest, 400)); }) .buildClient(); assertThrows(HttpResponseException.class, () -> configurationClient.setConfigurationSetting(key, null, value)); }
class ConfigurationClientBuilderTest extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String DEFAULT_DOMAIN_NAME = ".azconfig.io"; private static final String NAMESPACE_NAME = "dummyNamespaceName"; private final String key = "newKey"; private final String value = "newValue"; private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString(); static String connectionString = "Endpoint=http: @Test public void missingEndpoint() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.buildAsyncClient(); }); } @Test public void malformedURLExceptionForEndpoint() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.endpoint("htp: }); } @Test public void nullConnectionString() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString(null).buildAsyncClient(); }); } @Test public void emptyConnectionString() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("").buildAsyncClient(); }); } @Test public void missingSecretKey() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa;Secret=").buildAsyncClient(); }); } @Test public void missingId() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=;Secret=aaa").buildAsyncClient(); }); } @Test public void invalidConnectionStringSegmentCount() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa").buildAsyncClient(); }); } @Test public void nullAADCredential() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.endpoint(ENDPOINT).credential(null).buildAsyncClient(); }); } @Test public void timeoutPolicy() { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); final ConfigurationClient client = new ConfigurationClientBuilder() .connectionString(connectionString) .addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient(); assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void nullServiceVersion(HttpClient httpClient) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set."); final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder() .connectionString(connectionString) .retryPolicy(new RetryPolicy()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(null) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient); if (!interceptorManager.isPlaybackMode()) { clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value); assertEquals(addedSetting.getKey(), key); assertEquals(addedSetting.getValue(), value); } @Test public void defaultPipeline() { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set."); final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder() .connectionString(connectionString) .retryPolicy(new RetryPolicy()) .configuration(Configuration.getGlobalConfiguration()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .pipeline(new HttpPipelineBuilder().build()); if (!interceptorManager.isPlaybackMode()) { clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); assertThrows(HttpResponseException.class, () -> clientBuilder.buildClient().setConfigurationSetting(key, null, value)); } HttpClient defaultHttpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : new NettyAsyncHttpClientBuilder().wiretap(true).build(); clientBuilder.pipeline(null).httpClient(defaultHttpClient); ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value); assertEquals(addedSetting.getKey(), key); assertEquals(addedSetting.getValue(), value); } @Test @Test public void clientOptionHeadersAreAddedLast() { ConfigurationClient configurationClient = new ConfigurationClientBuilder() .connectionString(connectionString) .clientOptions(new ClientOptions() .setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) .httpClient(httpRequest -> { assertEquals("custom", httpRequest.getHeaders().getValue("User-Agent")); return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); }) .buildClient(); assertThrows(RuntimeException.class, () -> configurationClient.setConfigurationSetting(key, null, value)); } private static URI getURI(String endpointFormat, String namespace, String domainName) { try { return new URI(String.format(Locale.US, endpointFormat, namespace, domainName)); } catch (URISyntaxException exception) { throw new IllegalArgumentException(String.format(Locale.US, "Invalid namespace name: %s", namespace), exception); } } }
class ConfigurationClientBuilderTest extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String DEFAULT_DOMAIN_NAME = ".azconfig.io"; private static final String NAMESPACE_NAME = "dummyNamespaceName"; private final String key = "newKey"; private final String value = "newValue"; private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString(); static String connectionString = "Endpoint=http: @Test @DoNotRecord public void missingEndpoint() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.buildAsyncClient(); }); } @Test @DoNotRecord public void malformedURLExceptionForEndpoint() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.endpoint("htp: }); } @Test @DoNotRecord public void nullConnectionString() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString(null).buildAsyncClient(); }); } @Test @DoNotRecord public void emptyConnectionString() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("").buildAsyncClient(); }); } @Test @DoNotRecord public void missingSecretKey() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa;Secret=").buildAsyncClient(); }); } @Test @DoNotRecord public void missingId() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=;Secret=aaa").buildAsyncClient(); }); } @Test @DoNotRecord public void invalidConnectionStringSegmentCount() { assertThrows(IllegalArgumentException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa").buildAsyncClient(); }); } @Test @DoNotRecord public void nullAADCredential() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.endpoint(ENDPOINT).credential(null).buildAsyncClient(); }); } @Test @DoNotRecord public void timeoutPolicy() { final ConfigurationClient client = new ConfigurationClientBuilder() .connectionString(connectionString) .addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient(); assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.data.appconfiguration.TestHelper public void nullServiceVersion(HttpClient httpClient) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set."); final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder() .connectionString(connectionString) .retryPolicy(new RetryPolicy()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(null) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient); if (!interceptorManager.isPlaybackMode()) { clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value); assertEquals(addedSetting.getKey(), key); assertEquals(addedSetting.getValue(), value); } @Test public void defaultPipeline() { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set."); final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder() .connectionString(connectionString) .retryPolicy(new RetryPolicy()) .configuration(Configuration.getGlobalConfiguration()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .pipeline(new HttpPipelineBuilder().build()); if (!interceptorManager.isPlaybackMode()) { clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); assertThrows(HttpResponseException.class, () -> clientBuilder.buildClient().setConfigurationSetting(key, null, value)); } HttpClient defaultHttpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : new NettyAsyncHttpClientBuilder().wiretap(true).build(); clientBuilder.pipeline(null).httpClient(defaultHttpClient); ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value); assertEquals(addedSetting.getKey(), key); assertEquals(addedSetting.getValue(), value); } @Test @DoNotRecord @Test @DoNotRecord public void clientOptionHeadersAreAddedLast() { ConfigurationClient configurationClient = new ConfigurationClientBuilder() .connectionString(connectionString) .clientOptions(new ClientOptions() .setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) .httpClient(httpRequest -> { assertEquals("custom", httpRequest.getHeaders().getValue("User-Agent")); return Mono.just(new MockHttpResponse(httpRequest, 400)); }) .buildClient(); assertThrows(HttpResponseException.class, () -> configurationClient.setConfigurationSetting(key, null, value)); } private static URI getURI(String endpointFormat, String namespace, String domainName) { try { return new URI(String.format(Locale.US, endpointFormat, namespace, domainName)); } catch (URISyntaxException exception) { throw new IllegalArgumentException(String.format(Locale.US, "Invalid namespace name: %s", namespace), exception); } } }
There is a utility method in `CoreUtils` that will handle this. https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/util/CoreUtils.java#L277
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); String applicationId = clientOptions == null ? httpLogOptions.getApplicationId() : clientOptions.getApplicationId(); policies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); }
String applicationId =
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion); }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
better assert the authorities values here in addition to the size.
public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.containsClaim("roles")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); }
assertThat(principal.getAuthorities()).hasSize(2);
public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.containsClaim("roles")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assert.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assert.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); }
class AADB2CUserPrincipalTest { private Jwt jwt = mock(Jwt.class); private Map<String, Object> claims = new HashMap<>(); private Map<String, Object> headers = new HashMap<>(); private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { when(jwt.containsClaim("scp")).thenReturn(true); when(jwt.containsClaim("roles")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.containsClaim("scp")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.containsClaim("scp")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.containsClaim("roles")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } }
class AADB2CUserPrincipalTest { private Jwt jwt = mock(Jwt.class); private Map<String, Object> claims = new HashMap<>(); private Map<String, Object> headers = new HashMap<>(); private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { when(jwt.containsClaim("scp")).thenReturn(true); when(jwt.containsClaim("roles")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.containsClaim("scp")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assert.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assert.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.containsClaim("scp")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assert.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assert.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.containsClaim("roles")).thenReturn(true); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADB2COAuth2AuthenticatedPrincipal.class); AADB2COAuth2AuthenticatedPrincipal principal = (AADB2COAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assert.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assert.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assert.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
no need to check the output because this is not a correctness test.
public Mono<Void> runAsync() { return textAnalyticsAsyncClient.detectLanguage("Detta är ett dokument skrivet på engelska.") .flatMap( result -> "swedish".equals(result.getName()) ? Mono.empty() : Mono.error(new RuntimeException("Expected detected language."))); }
: Mono.error(new RuntimeException("Expected detected language.")));
public Mono<Void> runAsync() { return textAnalyticsAsyncClient.detectLanguageBatch(documents, "en", null).then(); }
class DetectLanguageTest extends ServiceTest<PerfStressOptions> { /** * The CustomModelRecognitionTest class. * * @param options the configurable options for perf testing this class */ public DetectLanguageTest(PerfStressOptions options) { super(options); } @Override public void run() { final DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage( "Detta är ett dokument skrivet på engelska."); assert "swedish".equals(detectedLanguage.getName()); } @Override }
class DetectLanguageTest extends ServiceTest<PerfStressOptions> { List<String> documents = new ArrayList<>(); /** * The DetectLanguageTest class. * * @param options the configurable options for perf testing this class */ public DetectLanguageTest(PerfStressOptions options) { super(options); final int documentSize = options.getCount(); for (int i = 0; i < documentSize; i++) { documents.add("Detta är ett dokument skrivet på engelska."); } } @Override public void run() { textAnalyticsClient.detectLanguageBatch(documents, "en", null); } @Override }
no need to check the output because this is not a correctness test.
public void run() { final DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage( "Detta är ett dokument skrivet på engelska."); assert "swedish".equals(detectedLanguage.getName()); }
assert "swedish".equals(detectedLanguage.getName());
public void run() { textAnalyticsClient.detectLanguageBatch(documents, "en", null); }
class DetectLanguageTest extends ServiceTest<PerfStressOptions> { /** * The CustomModelRecognitionTest class. * * @param options the configurable options for perf testing this class */ public DetectLanguageTest(PerfStressOptions options) { super(options); } @Override @Override public Mono<Void> runAsync() { return textAnalyticsAsyncClient.detectLanguage("Detta är ett dokument skrivet på engelska.") .flatMap( result -> "swedish".equals(result.getName()) ? Mono.empty() : Mono.error(new RuntimeException("Expected detected language."))); } }
class DetectLanguageTest extends ServiceTest<PerfStressOptions> { List<String> documents = new ArrayList<>(); /** * The DetectLanguageTest class. * * @param options the configurable options for perf testing this class */ public DetectLanguageTest(PerfStressOptions options) { super(options); final int documentSize = options.getCount(); for (int i = 0; i < documentSize; i++) { documents.add("Detta är ett dokument skrivet på engelska."); } } @Override @Override public Mono<Void> runAsync() { return textAnalyticsAsyncClient.detectLanguageBatch(documents, "en", null).then(); } }
You need to send a bunch of documents and make the default to be 1k which is the max the service accepts for this API.
public Mono<Void> runAsync() { return textAnalyticsAsyncClient.detectLanguage("Detta är ett dokument skrivet på engelska.") .flatMap( result -> "swedish".equals(result.getName()) ? Mono.empty() : Mono.error(new RuntimeException("Expected detected language."))); }
return textAnalyticsAsyncClient.detectLanguage("Detta är ett dokument skrivet på engelska.")
public Mono<Void> runAsync() { return textAnalyticsAsyncClient.detectLanguageBatch(documents, "en", null).then(); }
class DetectLanguageTest extends ServiceTest<PerfStressOptions> { /** * The CustomModelRecognitionTest class. * * @param options the configurable options for perf testing this class */ public DetectLanguageTest(PerfStressOptions options) { super(options); } @Override public void run() { final DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage( "Detta är ett dokument skrivet på engelska."); assert "swedish".equals(detectedLanguage.getName()); } @Override }
class DetectLanguageTest extends ServiceTest<PerfStressOptions> { List<String> documents = new ArrayList<>(); /** * The DetectLanguageTest class. * * @param options the configurable options for perf testing this class */ public DetectLanguageTest(PerfStressOptions options) { super(options); final int documentSize = options.getCount(); for (int i = 0; i < documentSize; i++) { documents.add("Detta är ett dokument skrivet på engelska."); } } @Override public void run() { textAnalyticsClient.detectLanguageBatch(documents, "en", null); } @Override }
Yes. Removed.
public Mono<Void> runAsync() { return textAnalyticsAsyncClient.detectLanguage("Detta är ett dokument skrivet på engelska.") .flatMap( result -> "swedish".equals(result.getName()) ? Mono.empty() : Mono.error(new RuntimeException("Expected detected language."))); }
: Mono.error(new RuntimeException("Expected detected language.")));
public Mono<Void> runAsync() { return textAnalyticsAsyncClient.detectLanguageBatch(documents, "en", null).then(); }
class DetectLanguageTest extends ServiceTest<PerfStressOptions> { /** * The CustomModelRecognitionTest class. * * @param options the configurable options for perf testing this class */ public DetectLanguageTest(PerfStressOptions options) { super(options); } @Override public void run() { final DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage( "Detta är ett dokument skrivet på engelska."); assert "swedish".equals(detectedLanguage.getName()); } @Override }
class DetectLanguageTest extends ServiceTest<PerfStressOptions> { List<String> documents = new ArrayList<>(); /** * The DetectLanguageTest class. * * @param options the configurable options for perf testing this class */ public DetectLanguageTest(PerfStressOptions options) { super(options); final int documentSize = options.getCount(); for (int i = 0; i < documentSize; i++) { documents.add("Detta är ett dokument skrivet på engelska."); } } @Override public void run() { textAnalyticsClient.detectLanguageBatch(documents, "en", null); } @Override }
Country asPhoneNumber? :) edit: same with other sample snippets
public void beginRecognizeIDDocumentFromUrl() { String idDocumentUrl = "idDocumentUrl"; formRecognizerAsyncClient.beginRecognizeIdDocumentsFromUrl(idDocumentUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedIDDocumentResult -> { for (int i = 0; i < recognizedIDDocumentResult.size(); i++) { RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized license info for page %d -----------%n", i); FormField firstNameField = recognizedFields.get("FirstName"); if (firstNameField != null) { if (FieldValueType.STRING == firstNameField.getValue().getValueType()) { String firstName = firstNameField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, firstNameField.getConfidence()); } } FormField lastNameField = recognizedFields.get("LastName"); if (lastNameField != null) { if (FieldValueType.STRING == lastNameField.getValue().getValueType()) { String lastName = lastNameField.getValue().asString(); System.out.printf("Last name: %s, confidence: %.2f%n", lastName, lastNameField.getConfidence()); } } FormField countryFormField = recognizedFields.get("Country"); if (countryFormField != null) { if (FieldValueType.STRING == countryFormField.getValue().getValueType()) { String country = countryFormField.getValue().asPhoneNumber(); System.out.printf("Country: %s, confidence: %.2f%n", country, countryFormField.getConfidence()); } } FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration"); if (dateOfExpirationField != null) { if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) { LocalDate expirationDate = dateOfExpirationField.getValue().asDate(); System.out.printf("Document date of expiration: %s, confidence: %.2f%n", expirationDate, dateOfExpirationField.getConfidence()); } } FormField documentNumberField = recognizedFields.get("DocumentNumber"); if (documentNumberField != null) { if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) { String documentNumber = documentNumberField.getValue().asString(); System.out.printf("Document number: %s, confidence: %.2f%n", documentNumber, documentNumberField.getConfidence()); } } } }); }
String country = countryFormField.getValue().asPhoneNumber();
public void beginRecognizeIDDocumentFromUrl() { String idDocumentUrl = "idDocumentUrl"; formRecognizerAsyncClient.beginRecognizeIdDocumentsFromUrl(idDocumentUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedIDDocumentResult -> { for (int i = 0; i < recognizedIDDocumentResult.size(); i++) { RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized license info for page %d -----------%n", i); FormField firstNameField = recognizedFields.get("FirstName"); if (firstNameField != null) { if (FieldValueType.STRING == firstNameField.getValue().getValueType()) { String firstName = firstNameField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, firstNameField.getConfidence()); } } FormField lastNameField = recognizedFields.get("LastName"); if (lastNameField != null) { if (FieldValueType.STRING == lastNameField.getValue().getValueType()) { String lastName = lastNameField.getValue().asString(); System.out.printf("Last name: %s, confidence: %.2f%n", lastName, lastNameField.getConfidence()); } } FormField countryFormField = recognizedFields.get("Country"); if (countryFormField != null) { if (FieldValueType.STRING == countryFormField.getValue().getValueType()) { String country = countryFormField.getValue().asCountry(); System.out.printf("Country: %s, confidence: %.2f%n", country, countryFormField.getConfidence()); } } FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration"); if (dateOfExpirationField != null) { if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) { LocalDate expirationDate = dateOfExpirationField.getValue().asDate(); System.out.printf("Document date of expiration: %s, confidence: %.2f%n", expirationDate, dateOfExpirationField.getConfidence()); } } FormField documentNumberField = recognizedFields.get("DocumentNumber"); if (documentNumberField != null) { if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) { String documentNumber = documentNumberField.getValue().asString(); System.out.printf("Document number: %s, confidence: %.2f%n", documentNumber, documentNumberField.getConfidence()); } } } }); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { private final FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String formUrl = "{formUrl}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldName, formField) -> { System.out.printf("Field text: %s%n", fieldName); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options */ public void beginRecognizeContentFromUrlWithOptions() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(), new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{receiptUrl}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receiptUrl}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setFieldElementsIncluded(includeFieldElements) .setLocale(FormRecognizerLocale.EN_US) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedReceipt = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setLocale(FormRecognizerLocale.EN_US) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrl() { String invoiceUrl = "invoice_url"; formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrlWithOptions() { String invoiceUrl = "invoice_url"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl, new RecognizeInvoicesOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeInvoices() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()))); formRecognizerAsyncClient.beginRecognizeInvoices(buffer, invoice.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeInvoicesWithOptions() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()))); formRecognizerAsyncClient.beginRecognizeInvoices(buffer, invoice.length(), new RecognizeInvoicesOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeIdDocumentsFromUrlWithOptions() { String licenseDocumentUrl = "licenseDocumentUrl"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeIdDocumentsFromUrl(licenseDocumentUrl, new RecognizeIDDocumentOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedIDDocumentResult -> { for (int i = 0; i < recognizedIDDocumentResult.size(); i++) { RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized license info for page %d -----------%n", i); FormField firstNameField = recognizedFields.get("FirstName"); if (firstNameField != null) { if (FieldValueType.STRING == firstNameField.getValue().getValueType()) { String firstName = firstNameField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, firstNameField.getConfidence()); } } FormField lastNameField = recognizedFields.get("LastName"); if (lastNameField != null) { if (FieldValueType.STRING == lastNameField.getValue().getValueType()) { String lastName = lastNameField.getValue().asString(); System.out.printf("Last name: %s, confidence: %.2f%n", lastName, lastNameField.getConfidence()); } } FormField countryFormField = recognizedFields.get("Country"); if (countryFormField != null) { if (FieldValueType.STRING == countryFormField.getValue().getValueType()) { String country = countryFormField.getValue().asPhoneNumber(); System.out.printf("Country: %s, confidence: %.2f%n", country, countryFormField.getConfidence()); } } FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration"); if (dateOfExpirationField != null) { if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) { LocalDate expirationDate = dateOfExpirationField.getValue().asDate(); System.out.printf("Document date of expiration: %s, confidence: %.2f%n", expirationDate, dateOfExpirationField.getConfidence()); } } FormField documentNumberField = recognizedFields.get("DocumentNumber"); if (documentNumberField != null) { if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) { String documentNumber = documentNumberField.getValue().asString(); System.out.printf("Document number: %s, confidence: %.2f%n", documentNumber, documentNumberField.getConfidence()); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeIDDocuments() throws IOException { File license = new File("local/file_path/license.jpg"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(license.toPath()))); formRecognizerAsyncClient.beginRecognizeIdDocuments(buffer, license.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedIDDocumentResult -> { for (int i = 0; i < recognizedIDDocumentResult.size(); i++) { RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized license info for page %d -----------%n", i); FormField firstNameField = recognizedFields.get("FirstName"); if (firstNameField != null) { if (FieldValueType.STRING == firstNameField.getValue().getValueType()) { String firstName = firstNameField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, firstNameField.getConfidence()); } } FormField lastNameField = recognizedFields.get("LastName"); if (lastNameField != null) { if (FieldValueType.STRING == lastNameField.getValue().getValueType()) { String lastName = lastNameField.getValue().asString(); System.out.printf("Last name: %s, confidence: %.2f%n", lastName, lastNameField.getConfidence()); } } FormField countryFormField = recognizedFields.get("Country"); if (countryFormField != null) { if (FieldValueType.STRING == countryFormField.getValue().getValueType()) { String country = countryFormField.getValue().asPhoneNumber(); System.out.printf("Country: %s, confidence: %.2f%n", country, countryFormField.getConfidence()); } } FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration"); if (dateOfExpirationField != null) { if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) { LocalDate expirationDate = dateOfExpirationField.getValue().asDate(); System.out.printf("Document date of expiration: %s, confidence: %.2f%n", expirationDate, dateOfExpirationField.getConfidence()); } } FormField documentNumberField = recognizedFields.get("DocumentNumber"); if (documentNumberField != null) { if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) { String documentNumber = documentNumberField.getValue().asString(); System.out.printf("Document number: %s, confidence: %.2f%n", documentNumber, documentNumberField.getConfidence()); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeIDDocumentsWithOptions() throws IOException { File licenseDocument = new File("local/file_path/license.jpg"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(licenseDocument.toPath()))); formRecognizerAsyncClient.beginRecognizeIdDocuments(buffer, licenseDocument.length(), new RecognizeIDDocumentOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedIDDocumentResult -> { for (int i = 0; i < recognizedIDDocumentResult.size(); i++) { RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized license info for page %d -----------%n", i); FormField firstNameField = recognizedFields.get("FirstName"); if (firstNameField != null) { if (FieldValueType.STRING == firstNameField.getValue().getValueType()) { String firstName = firstNameField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, firstNameField.getConfidence()); } } FormField lastNameField = recognizedFields.get("LastName"); if (lastNameField != null) { if (FieldValueType.STRING == lastNameField.getValue().getValueType()) { String lastName = lastNameField.getValue().asString(); System.out.printf("Last name: %s, confidence: %.2f%n", lastName, lastNameField.getConfidence()); } } FormField countryFormField = recognizedFields.get("Country"); if (countryFormField != null) { if (FieldValueType.STRING == countryFormField.getValue().getValueType()) { String country = countryFormField.getValue().asPhoneNumber(); System.out.printf("Country: %s, confidence: %.2f%n", country, countryFormField.getConfidence()); } } FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration"); if (dateOfExpirationField != null) { if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) { LocalDate expirationDate = dateOfExpirationField.getValue().asDate(); System.out.printf("Document date of expiration: %s, confidence: %.2f%n", expirationDate, dateOfExpirationField.getConfidence()); } } FormField documentNumberField = recognizedFields.get("DocumentNumber"); if (documentNumberField != null) { if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) { String documentNumber = documentNumberField.getValue().asString(); System.out.printf("Document number: %s, confidence: %.2f%n", documentNumber, documentNumberField.getConfidence()); } } } }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { private final FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String formUrl = "{formUrl}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldName, formField) -> { System.out.printf("Field text: %s%n", fieldName); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options */ public void beginRecognizeContentFromUrlWithOptions() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(), new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{receiptUrl}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receiptUrl}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setFieldElementsIncluded(includeFieldElements) .setLocale(FormRecognizerLocale.EN_US) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedReceipt = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setLocale(FormRecognizerLocale.EN_US) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrl() { String invoiceUrl = "invoice_url"; formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrlWithOptions() { String invoiceUrl = "invoice_url"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl, new RecognizeInvoicesOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeInvoices() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()))); formRecognizerAsyncClient.beginRecognizeInvoices(buffer, invoice.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeInvoicesWithOptions() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()))); formRecognizerAsyncClient.beginRecognizeInvoices(buffer, invoice.length(), new RecognizeInvoicesOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeIdDocumentsFromUrlWithOptions() { String licenseDocumentUrl = "licenseDocumentUrl"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeIdDocumentsFromUrl(licenseDocumentUrl, new RecognizeIdDocumentOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedIDDocumentResult -> { for (int i = 0; i < recognizedIDDocumentResult.size(); i++) { RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized license info for page %d -----------%n", i); FormField firstNameField = recognizedFields.get("FirstName"); if (firstNameField != null) { if (FieldValueType.STRING == firstNameField.getValue().getValueType()) { String firstName = firstNameField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, firstNameField.getConfidence()); } } FormField lastNameField = recognizedFields.get("LastName"); if (lastNameField != null) { if (FieldValueType.STRING == lastNameField.getValue().getValueType()) { String lastName = lastNameField.getValue().asString(); System.out.printf("Last name: %s, confidence: %.2f%n", lastName, lastNameField.getConfidence()); } } FormField countryFormField = recognizedFields.get("Country"); if (countryFormField != null) { if (FieldValueType.STRING == countryFormField.getValue().getValueType()) { String country = countryFormField.getValue().asCountry(); System.out.printf("Country: %s, confidence: %.2f%n", country, countryFormField.getConfidence()); } } FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration"); if (dateOfExpirationField != null) { if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) { LocalDate expirationDate = dateOfExpirationField.getValue().asDate(); System.out.printf("Document date of expiration: %s, confidence: %.2f%n", expirationDate, dateOfExpirationField.getConfidence()); } } FormField documentNumberField = recognizedFields.get("DocumentNumber"); if (documentNumberField != null) { if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) { String documentNumber = documentNumberField.getValue().asString(); System.out.printf("Document number: %s, confidence: %.2f%n", documentNumber, documentNumberField.getConfidence()); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeIDDocuments() throws IOException { File license = new File("local/file_path/license.jpg"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(license.toPath()))); formRecognizerAsyncClient.beginRecognizeIdDocuments(buffer, license.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedIDDocumentResult -> { for (int i = 0; i < recognizedIDDocumentResult.size(); i++) { RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized license info for page %d -----------%n", i); FormField firstNameField = recognizedFields.get("FirstName"); if (firstNameField != null) { if (FieldValueType.STRING == firstNameField.getValue().getValueType()) { String firstName = firstNameField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, firstNameField.getConfidence()); } } FormField lastNameField = recognizedFields.get("LastName"); if (lastNameField != null) { if (FieldValueType.STRING == lastNameField.getValue().getValueType()) { String lastName = lastNameField.getValue().asString(); System.out.printf("Last name: %s, confidence: %.2f%n", lastName, lastNameField.getConfidence()); } } FormField countryFormField = recognizedFields.get("Country"); if (countryFormField != null) { if (FieldValueType.STRING == countryFormField.getValue().getValueType()) { String country = countryFormField.getValue().asCountry(); System.out.printf("Country: %s, confidence: %.2f%n", country, countryFormField.getConfidence()); } } FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration"); if (dateOfExpirationField != null) { if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) { LocalDate expirationDate = dateOfExpirationField.getValue().asDate(); System.out.printf("Document date of expiration: %s, confidence: %.2f%n", expirationDate, dateOfExpirationField.getConfidence()); } } FormField documentNumberField = recognizedFields.get("DocumentNumber"); if (documentNumberField != null) { if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) { String documentNumber = documentNumberField.getValue().asString(); System.out.printf("Document number: %s, confidence: %.2f%n", documentNumber, documentNumberField.getConfidence()); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeIDDocumentsWithOptions() throws IOException { File licenseDocument = new File("local/file_path/license.jpg"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(licenseDocument.toPath()))); formRecognizerAsyncClient.beginRecognizeIdDocuments(buffer, licenseDocument.length(), new RecognizeIdDocumentOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedIDDocumentResult -> { for (int i = 0; i < recognizedIDDocumentResult.size(); i++) { RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized license info for page %d -----------%n", i); FormField firstNameField = recognizedFields.get("FirstName"); if (firstNameField != null) { if (FieldValueType.STRING == firstNameField.getValue().getValueType()) { String firstName = firstNameField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, firstNameField.getConfidence()); } } FormField lastNameField = recognizedFields.get("LastName"); if (lastNameField != null) { if (FieldValueType.STRING == lastNameField.getValue().getValueType()) { String lastName = lastNameField.getValue().asString(); System.out.printf("Last name: %s, confidence: %.2f%n", lastName, lastNameField.getConfidence()); } } FormField countryFormField = recognizedFields.get("Country"); if (countryFormField != null) { if (FieldValueType.STRING == countryFormField.getValue().getValueType()) { String country = countryFormField.getValue().asCountry(); System.out.printf("Country: %s, confidence: %.2f%n", country, countryFormField.getConfidence()); } } FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration"); if (dateOfExpirationField != null) { if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) { LocalDate expirationDate = dateOfExpirationField.getValue().asDate(); System.out.printf("Document date of expiration: %s, confidence: %.2f%n", expirationDate, dateOfExpirationField.getConfidence()); } } FormField documentNumberField = recognizedFields.get("DocumentNumber"); if (documentNumberField != null) { if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) { String documentNumber = documentNumberField.getValue().asString(); System.out.printf("Document number: %s, confidence: %.2f%n", documentNumber, documentNumberField.getConfidence()); } } } }); } }
should be cased "URI"
static URI convertToUri(String uri) throws IllegalArgumentException { try { return new URI(uri); } catch (Exception e) { throw new IllegalArgumentException("Invalid uri format", e); } }
throw new IllegalArgumentException("Invalid uri format", e);
static URI convertToUri(String uri) throws IllegalArgumentException { try { return new URI(uri); } catch (Exception e) { throw new IllegalArgumentException("Invalid URI format", e); } }
class ModelsRepositoryClientBuilder { private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static URI globalRepositoryUri; static { try { globalRepositoryUri = new URI(ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT); } catch (URISyntaxException e) { } } private final List<HttpPipelinePolicy> additionalPolicies; private URI repositoryEndpoint; private ModelDependencyResolution modelDependencyResolution = ModelDependencyResolution.TRY_FROM_EXPANDED; private ModelsRepositoryServiceVersion serviceVersion; private ClientOptions clientOptions; private HttpPipeline httpPipeline; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(null, null); private final Map<String, String> properties; private Configuration configuration; /** * The public constructor for ModelsRepositoryClientBuilder */ public ModelsRepositoryClientBuilder() { additionalPolicies = new ArrayList<>(); properties = CoreUtils.getProperties(MODELS_REPOSITORY_PROPERTIES); httpLogOptions = new HttpLogOptions(); this.repositoryEndpoint = globalRepositoryUri; } private static HttpPipeline constructPipeline( HttpLogOptions httpLogOptions, ClientOptions clientOptions, HttpClient httpClient, List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy, Configuration configuration, Map<String, String> properties) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = clientOptions == null ? httpLogOptions.getApplicationId() : clientOptions.getApplicationId(); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); policies.add(new AddDatePolicy()); policies.addAll(additionalPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Create a {@link ModelsRepositoryClient} based on the builder settings. * * @return the created synchronous ModelsRepotioryClient */ public ModelsRepositoryClient buildClient() { return new ModelsRepositoryClient(buildAsyncClient()); } /** * Create a {@link ModelsRepositoryAsyncClient} based on the builder settings. * * @return the created asynchronous ModelsRepositoryAsyncClient */ public ModelsRepositoryAsyncClient buildAsyncClient() { Configuration buildConfiguration = this.configuration; if (buildConfiguration == null) { buildConfiguration = Configuration.getGlobalConfiguration().clone(); } ModelsRepositoryServiceVersion serviceVersion = this.serviceVersion; if (serviceVersion == null) { serviceVersion = ModelsRepositoryServiceVersion.getLatest(); } RetryPolicy retryPolicy = this.retryPolicy; if (retryPolicy == null) { retryPolicy = DEFAULT_RETRY_POLICY; } if (this.httpPipeline == null) { this.httpPipeline = constructPipeline( this.httpLogOptions, this.clientOptions, this.httpClient, this.additionalPolicies, retryPolicy, buildConfiguration, this.properties); } return new ModelsRepositoryAsyncClient( this.repositoryEndpoint, this.httpPipeline, serviceVersion, this.modelDependencyResolution); } /** * Set the default dependency resolution option that the built client will use. This field will have a default value. * * @param modelDependencyResolution A DependencyResolutionOption value to force model resolution behavior. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder modelDependencyResolution(ModelDependencyResolution modelDependencyResolution) { this.modelDependencyResolution = modelDependencyResolution; return this; } /** * Set the service endpoint that the built client will communicate with. This field is mandatory to set. * * @param repositoryEndpoint Uri of the service in String format. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder repositoryEndpoint(String repositoryEndpoint) { this.repositoryEndpoint = convertToUri(repositoryEndpoint); return this; } /** * Sets the {@link ModelsRepositoryServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param serviceVersion The service API version to use. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder serviceVersion(ModelsRepositoryServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the {@link HttpClient} to use for sending a receiving requests to and from the service. * * @param httpClient HttpClient to use for requests. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. * @throws NullPointerException If {@code httpLogOptions} is {@code null}. */ public ModelsRepositoryClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If * the method is called multiple times, all policies will be added and their order preserved. * * @param pipelinePolicy a pipeline policy * @return the updated ModelsRepositoryClientBuilder instance for fluent building. * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ public ModelsRepositoryClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null")); return this; } /** * Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent. * <p> * The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy * For implementing custom retry logic, see {@link RetryPolicy} as an example. * * @param retryPolicy the retry policy applied to each request. * @return The updated ConfigurationClientBuilder object. */ public ModelsRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * * @param httpPipeline HttpPipeline to use for sending service requests and receiving responses. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { 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 ModelsRepositoryClientBuilder object for fluent building. */ public ModelsRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions the {@link ClientOptions} to be set on the client. * @return The updated KeyClientBuilder object. */ public ModelsRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Converts a string to {@link URI} * * @param uri String format of the path * @return {@link URI} representation of the path/uri. * @throws IllegalArgumentException If the {@code uri} is invalid. */ }
class ModelsRepositoryClientBuilder { private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static URI globalRepositoryUri; static { try { globalRepositoryUri = new URI(ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT); } catch (URISyntaxException e) { } } private final List<HttpPipelinePolicy> additionalPolicies; private URI repositoryEndpoint; private ModelDependencyResolution modelDependencyResolution = ModelDependencyResolution.TRY_FROM_EXPANDED; private ModelsRepositoryServiceVersion serviceVersion; private ClientOptions clientOptions; private HttpPipeline httpPipeline; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(null, null); private final Map<String, String> properties; private Configuration configuration; /** * The public constructor for ModelsRepositoryClientBuilder */ public ModelsRepositoryClientBuilder() { additionalPolicies = new ArrayList<>(); properties = CoreUtils.getProperties(MODELS_REPOSITORY_PROPERTIES); httpLogOptions = new HttpLogOptions(); this.repositoryEndpoint = globalRepositoryUri; } private static HttpPipeline constructPipeline( HttpLogOptions httpLogOptions, ClientOptions clientOptions, HttpClient httpClient, List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy, Configuration configuration, Map<String, String> properties) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = clientOptions == null ? httpLogOptions.getApplicationId() : clientOptions.getApplicationId(); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); policies.add(new AddDatePolicy()); policies.addAll(additionalPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Create a {@link ModelsRepositoryClient} based on the builder settings. * * @return the created synchronous ModelsRepotioryClient */ public ModelsRepositoryClient buildClient() { return new ModelsRepositoryClient(buildAsyncClient()); } /** * Create a {@link ModelsRepositoryAsyncClient} based on the builder settings. * * @return the created asynchronous ModelsRepositoryAsyncClient */ public ModelsRepositoryAsyncClient buildAsyncClient() { Configuration buildConfiguration = this.configuration; if (buildConfiguration == null) { buildConfiguration = Configuration.getGlobalConfiguration().clone(); } ModelsRepositoryServiceVersion serviceVersion = this.serviceVersion; if (serviceVersion == null) { serviceVersion = ModelsRepositoryServiceVersion.getLatest(); } RetryPolicy retryPolicy = this.retryPolicy; if (retryPolicy == null) { retryPolicy = DEFAULT_RETRY_POLICY; } if (this.httpPipeline == null) { this.httpPipeline = constructPipeline( this.httpLogOptions, this.clientOptions, this.httpClient, this.additionalPolicies, retryPolicy, buildConfiguration, this.properties); } return new ModelsRepositoryAsyncClient( this.repositoryEndpoint, this.httpPipeline, serviceVersion, this.modelDependencyResolution); } /** * Set the default dependency resolution option that the built client will use. This field will have a default value. * * @param modelDependencyResolution A DependencyResolutionOption value to force model resolution behavior. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder modelDependencyResolution(ModelDependencyResolution modelDependencyResolution) { this.modelDependencyResolution = modelDependencyResolution; return this; } /** * Set the service endpoint that the built client will communicate with. This field is mandatory to set. * * @param repositoryEndpoint Uri of the service in String format. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder repositoryEndpoint(String repositoryEndpoint) { this.repositoryEndpoint = convertToUri(repositoryEndpoint); return this; } /** * Sets the {@link ModelsRepositoryServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param serviceVersion The service API version to use. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder serviceVersion(ModelsRepositoryServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the {@link HttpClient} to use for sending a receiving requests to and from the service. * * @param httpClient HttpClient to use for requests. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. * @throws NullPointerException If {@code httpLogOptions} is {@code null}. */ public ModelsRepositoryClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If * the method is called multiple times, all policies will be added and their order preserved. * * @param pipelinePolicy a pipeline policy * @return the updated ModelsRepositoryClientBuilder instance for fluent building. * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ public ModelsRepositoryClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null")); return this; } /** * Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent. * <p> * The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy * For implementing custom retry logic, see {@link RetryPolicy} as an example. * * @param retryPolicy the retry policy applied to each request. * @return The updated ConfigurationClientBuilder object. */ public ModelsRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * * @param httpPipeline HttpPipeline to use for sending service requests and receiving responses. * @return the updated ModelsRepositoryClientBuilder instance for fluent building. */ public ModelsRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { 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 ModelsRepositoryClientBuilder object for fluent building. */ public ModelsRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions the {@link ClientOptions} to be set on the client. * @return The updated KeyClientBuilder object. */ public ModelsRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Converts a string to {@link URI} * * @param uri String format of the path * @return {@link URI} representation of the path/uri. * @throws IllegalArgumentException If the {@code uri} is invalid. */ }
The spec calls for the string to be all capital. I suggest you do equalsIgnoreCase(..) to be safe.
public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } String authorizationType = keyValues.get("Authorization"); if (authorizationType != null && authorizationType.equals("aad") && this.credential == null) { String clientId = keyValues.get("AppId"); if (clientId != null) { this.credential = new DefaultAzureCredentialBuilder() .managedIdentityClientId(clientId) .build(); } else { this.credential = new DefaultAzureCredentialBuilder() .build(); } } this.connectionString = connectionString; return this; }
if (authorizationType != null && authorizationType.equals("aad") && this.credential == null) {
public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } this.connectionString = connectionString; return this; }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); ndjsonModule.addSerializer(new NdJsonSerializer()); jacksonAdapter.serializer().registerModule(ndjsonModule); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
Any other validation needed?
public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } String authorizationType = keyValues.get("Authorization"); if (authorizationType != null && authorizationType.equals("aad") && this.credential == null) { String clientId = keyValues.get("AppId"); if (clientId != null) { this.credential = new DefaultAzureCredentialBuilder() .managedIdentityClientId(clientId) .build(); } else { this.credential = new DefaultAzureCredentialBuilder() .build(); } } this.connectionString = connectionString; return this; }
if (clientId != null) {
public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } this.connectionString = connectionString; return this; }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); ndjsonModule.addSerializer(new NdJsonSerializer()); jacksonAdapter.serializer().registerModule(ndjsonModule); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
Not going through the connection string route
public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } String authorizationType = keyValues.get("Authorization"); if (authorizationType != null && authorizationType.equals("aad") && this.credential == null) { String clientId = keyValues.get("AppId"); if (clientId != null) { this.credential = new DefaultAzureCredentialBuilder() .managedIdentityClientId(clientId) .build(); } else { this.credential = new DefaultAzureCredentialBuilder() .build(); } } this.connectionString = connectionString; return this; }
if (clientId != null) {
public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } this.connectionString = connectionString; return this; }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); ndjsonModule.addSerializer(new NdJsonSerializer()); jacksonAdapter.serializer().registerModule(ndjsonModule); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
Add playback tests for this.
MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); }
if (this.credential != null) {
MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); ndjsonModule.addSerializer(new NdJsonSerializer()); jacksonAdapter.serializer().registerModule(ndjsonModule); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } this.connectionString = connectionString; return this; } /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } this.connectionString = connectionString; return this; } /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
Playback test added
MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); }
if (this.credential != null) {
MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); ndjsonModule.addSerializer(new NdJsonSerializer()); jacksonAdapter.serializer().registerModule(ndjsonModule); restServiceClientBuilder.serializerAdapter(jacksonAdapter); if (this.credential != null) { BearerTokenAuthenticationPolicy authenticationPolicy = new BearerTokenAuthenticationPolicy(this.credential, APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE); restServiceClientBuilder.addPolicy(authenticationPolicy); } ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } this.connectionString = connectionString; return this; } /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
class AzureMonitorExporterBuilder { private static final String APPLICATIONINSIGHTS_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING"; private static final String APPLICATIONINSIGHTS_AUTHENTICATION_SCOPE = "https: private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; private String connectionString; private AzureMonitorExporterServiceVersion serviceVersion; private TokenCredential credential; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); 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 to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); 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 AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The client options. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder clientOptions(ClientOptions clientOptions) { restServiceClientBuilder.clientOptions(clientOptions); return this; } /** * Sets the connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } this.connectionString = connectionString; return this; } /** * Sets the Azure Monitor service version. * * @param serviceVersion The Azure Monitor service version. * @return The update {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder serviceVersion(AzureMonitorExporterServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the token credential required for authentication with the ingestion endpoint service. * * @param credential The Azure Identity TokenCredential. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder credential(TokenCredential credential) { this.credential = credential; return this; } private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ /** * Creates an {@link AzureMonitorTraceExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorTraceExporter}. * @throws NullPointerException if the connection string is not set on this builder or if the environment variable * "APPLICATIONINSIGHTS_CONNECTION_STRING" is not set. */ public AzureMonitorTraceExporter buildTraceExporter() { if (this.connectionString == null) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); connectionString(configuration.get(APPLICATIONINSIGHTS_CONNECTION_STRING)); } Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorTraceExporter(buildAsyncClient(), instrumentationKey); } }
nit: please use static import of `Assert` to avoid adding that as a prefix to be consistent with other tests
public void expireRecord(OperationType operationType, boolean requestSent, Class<?> exceptionType) throws URISyntaxException { RntbdRequestArgs requestArgs = new RntbdRequestArgs( RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, ResourceType.Document), new URI("http: ); RntbdRequestTimer requestTimer = new RntbdRequestTimer(5000, 5000); RntbdRequestRecord record = new AsyncRntbdRequestRecord(requestArgs, requestTimer); if (requestSent) { record.setSendingRequestHasStarted(); } record.expire(); try{ record.get(); Assert.fail("RntbdRequestRecord should complete with exception"); } catch (ExecutionException e) { Throwable innerException = e.getCause(); assertThat(innerException).isInstanceOf(exceptionType); } catch (Exception e) { Assert.fail(); } }
Assert.fail("RntbdRequestRecord should complete with exception");
public void expireRecord(OperationType operationType, boolean requestSent, Class<?> exceptionType) throws URISyntaxException { RntbdRequestArgs requestArgs = new RntbdRequestArgs( RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, ResourceType.Document), new URI("http: ); RntbdRequestTimer requestTimer = new RntbdRequestTimer(5000, 5000); RntbdRequestRecord record = new AsyncRntbdRequestRecord(requestArgs, requestTimer); if (requestSent) { record.setSendingRequestHasStarted(); } record.expire(); try{ record.get(); fail("RntbdRequestRecord should complete with exception"); } catch (ExecutionException e) { Throwable innerException = e.getCause(); assertThat(innerException).isInstanceOf(exceptionType); } catch (Exception e) { fail("Wrong exception"); } }
class } }; } @Test(groups = { "unit" }
class } }; } @Test(groups = { "unit" }
GoneException in the cosmos context means that "The requested resource is no longer available at the server". Why are we reusing that exception here? I understand that GoneException is wired properly for retries but would'nt it make sense to have a client specific exception here which will make it easier to debug? Thoughts?
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else if (!this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
error = new GoneException(this.toString(), null, this.args.physicalAddress());
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly() || !this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
On a side note can we merge these two if conditions? (exclusive of above comment which is a bigger change)
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else if (!this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
error = new GoneException(this.toString(), null, this.args.physicalAddress());
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly() || !this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
yup, sure, will combine in the next iteration
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else if (!this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
error = new GoneException(this.toString(), null, this.args.physicalAddress());
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly() || !this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
Now that we have added support for SEQUENCE and VALUE, why do we still throw an exception here?
public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return BinaryData.fromBytes(amqpAnnotatedMessage.getBody().getFirstData()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new IllegalStateException("Message body type is not DATA, instead " + "it is: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
"it is: " + type.toString()));
public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return BinaryData.fromBytes(amqpAnnotatedMessage.getBody().getFirstData()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new IllegalStateException("Message body type is not DATA, instead " + "it is: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
class ServiceBusMessage { private static final int MAX_MESSAGE_ID_LENGTH = 128; private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final int MAX_SESSION_ID_LENGTH = 128; private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} with a {@link StandardCharsets * * @param body The content of the Service Bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into {@link * BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(body.toBytes())); } /** * This constructor provides an easy way to create {@link ServiceBusMessage} with message body as AMQP Data types * {@code SEQUENCE} and {@code VALUE}. It support sending and receiving of only one AMQP Sequence at present. * If you are sending message with single byte array or String data, you can also use other constructor. * * @param amqpMessageBody amqp message body. * * @throws NullPointerException if {@code amqpMessageBody} is {@code null}. */ public ServiceBusMessage(AmqpMessageBody amqpMessageBody) { Objects.requireNonNull(amqpMessageBody, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. * @throws UnsupportedOperationException if {@link AmqpMessageBodyType} is {@link AmqpMessageBodyType * or {@link AmqpMessageBodyType * @throws IllegalStateException for invalid {@link AmqpMessageBodyType}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); final AmqpMessageBodyType bodyType = receivedMessage.getRawAmqpMessage().getBody().getBodyType(); AmqpMessageBody amqpMessageBody; switch (bodyType) { case DATA: amqpMessageBody = AmqpMessageBody.fromData(receivedMessage.getRawAmqpMessage().getBody() .getFirstData()); break; case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException( "This constructor only supports the AMQP Data body type at present. Track this issue, " + "https: + "future.")); default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); final AmqpMessageProperties receivedProperties = receivedMessage.getRawAmqpMessage().getProperties(); final AmqpMessageProperties newProperties = amqpAnnotatedMessage.getProperties(); newProperties.setMessageId(receivedProperties.getMessageId()); newProperties.setUserId(receivedProperties.getUserId()); newProperties.setTo(receivedProperties.getTo()); newProperties.setSubject(receivedProperties.getSubject()); newProperties.setReplyTo(receivedProperties.getReplyTo()); newProperties.setCorrelationId(receivedProperties.getCorrelationId()); newProperties.setContentType(receivedProperties.getContentType()); newProperties.setContentEncoding(receivedProperties.getContentEncoding()); newProperties.setAbsoluteExpiryTime(receivedProperties.getAbsoluteExpiryTime()); newProperties.setCreationTime(receivedProperties.getCreationTime()); newProperties.setGroupId(receivedProperties.getGroupId()); newProperties.setGroupSequence(receivedProperties.getGroupSequence()); newProperties.setReplyToGroupId(receivedProperties.getReplyToGroupId()); final AmqpMessageHeader receivedHeader = receivedMessage.getRawAmqpMessage().getHeader(); final AmqpMessageHeader newHeader = this.amqpAnnotatedMessage.getHeader(); newHeader.setPriority(receivedHeader.getPriority()); newHeader.setTimeToLive(receivedHeader.getTimeToLive()); newHeader.setDurable(receivedHeader.isDurable()); newHeader.setFirstAcquirer(receivedHeader.isFirstAcquirer()); final Map<String, Object> receivedAnnotations = receivedMessage.getRawAmqpMessage() .getMessageAnnotations(); final Map<String, Object> newAnnotations = this.amqpAnnotatedMessage.getMessageAnnotations(); for (Map.Entry<String, Object> entry : receivedAnnotations.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == LOCKED_UNTIL_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_TIME_UTC_ANNOTATION_NAME) { continue; } newAnnotations.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedDelivery = receivedMessage.getRawAmqpMessage().getDeliveryAnnotations(); final Map<String, Object> newDelivery = this.amqpAnnotatedMessage.getDeliveryAnnotations(); for (Map.Entry<String, Object> entry : receivedDelivery.entrySet()) { newDelivery.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedFooter = receivedMessage.getRawAmqpMessage().getFooter(); final Map<String, Object> newFooter = this.amqpAnnotatedMessage.getFooter(); for (Map.Entry<String, Object> entry : receivedFooter.entrySet()) { newFooter.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedApplicationProperties = receivedMessage.getRawAmqpMessage() .getApplicationProperties(); final Map<String, Object> newApplicationProperties = this.amqpAnnotatedMessage.getApplicationProperties(); for (Map.Entry<String, Object> entry : receivedApplicationProperties.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_REASON_ANNOTATION_NAME) { continue; } newApplicationProperties.put(entry.getKey(), entry.getValue()); } this.context = Context.NONE; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code * getApplicationProperties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides convenience APIs to serialize/deserialize the object.</p> * * <p>If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use * of {@link * consumers who wish to deserialize the binary data.</p> * * @throws IllegalStateException if called for the messages which are not of binary data type. * @return Binary data representing the payload. */ /** * Gets the content type of the message. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * @return The content type of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * * @param contentType RFC2045 Content-Type descriptor of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return The correlation id of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { String correlationId = null; AmqpMessageId amqpCorrelationId = amqpAnnotatedMessage.getProperties().getCorrelationId(); if (amqpCorrelationId != null) { correlationId = amqpCorrelationId.toString(); } return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { AmqpMessageId id = null; if (correlationId != null) { id = new AmqpMessageId(correlationId); } amqpAnnotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the subject for the message. * * <p> * This property enables the application to indicate the purpose of the message to the receiver in a standardized * fashion, similar to an email subject line. The mapped AMQP property is "subject". * </p> * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The application specific subject. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If * enabled, the * <a href="https: * feature identifies and removes second and further submissions of messages with the same {@code messageId}. * </p> * * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { String messageId = null; AmqpMessageId amqpMessageId = amqpAnnotatedMessage.getProperties().getMessageId(); if (amqpMessageId != null) { messageId = amqpMessageId.toString(); } return messageId; } /** * Sets the message id. * * @param messageId The message id to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public ServiceBusMessage setMessageId(String messageId) { checkIdLength("messageId", messageId, MAX_MESSAGE_ID_LENGTH); AmqpMessageId id = null; if (messageId != null) { id = new AmqpMessageId(messageId); } amqpAnnotatedMessage.getProperties().setMessageId(id); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * </p> * * @return The partition key of this message. * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey The partition key of this message. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code partitionKey} is too long or if the {@code partitionKey} does not * match the {@code sessionId}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { checkIdLength("partitionKey", partitionKey, MAX_PARTITION_KEY_LENGTH); checkPartitionKey(partitionKey); amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return The raw AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return amqpAnnotatedMessage; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { String replyTo = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getReplyTo(); if (amqpAddress != null) { replyTo = amqpAddress.toString(); } return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { AmqpAddress replyToAddress = null; if (replyTo != null) { replyToAddress = new AmqpAddress(replyTo); } amqpAnnotatedMessage.getProperties().setReplyTo(replyToAddress); return this; } /** * Gets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @return "To" property value of this message */ public String getTo() { String to = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getTo(); if (amqpAddress != null) { to = amqpAddress.toString(); } return to; } /** * Sets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @param to To property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { AmqpAddress toAddress = null; if (to != null) { toAddress = new AmqpAddress(to); } amqpAnnotatedMessage.getProperties().setTo(toAddress); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the {@link * be set for the reply when sent to the reply entity. * * @return The {@code getReplyToGroupId} property value of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId The ReplyToGroupId property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the session identifier for a session-aware entity. * * <p> * For session-aware entities, this application-defined value specifies the session affiliation of the message. * Messages with the same session identifier are subject to summary locking and enable exact in-order processing and * demultiplexing. For session-unaware entities, this value is ignored. See <a * href="https: * </p> * * @return The session id of the {@link ServiceBusMessage}. * @see <a href="https: */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session identifier for a session-aware entity. * * @param sessionId The session identifier to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code sessionId} is too long or if the {@code sessionId} does not match * the {@code partitionKey}. */ public ServiceBusMessage setSessionId(String sessionId) { checkIdLength("sessionId", sessionId, MAX_SESSION_ID_LENGTH); checkSessionId(sessionId); amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /** * Checks the length of ID fields. * * Some fields within the message will cause a failure in the service without enough context information. */ private void checkIdLength(String fieldName, String value, int maxLength) { if (value != null && value.length() > maxLength) { final String message = String.format("%s cannot be longer than %d characters.", fieldName, maxLength); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkSessionId(String proposedSessionId) { if (proposedSessionId == null) { return; } if (this.getPartitionKey() != null && this.getPartitionKey().compareTo(proposedSessionId) != 0) { final String message = String.format( "sessionId:%s cannot be set to a different value than partitionKey:%s.", proposedSessionId, this.getPartitionKey()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkPartitionKey(String proposedPartitionKey) { if (proposedPartitionKey == null) { return; } if (this.getSessionId() != null && this.getSessionId().compareTo(proposedPartitionKey) != 0) { final String message = String.format( "partitionKey:%s cannot be set to a different value than sessionId:%s.", proposedPartitionKey, this.getSessionId()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } }
class ServiceBusMessage { private static final int MAX_MESSAGE_ID_LENGTH = 128; private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final int MAX_SESSION_ID_LENGTH = 128; private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} with a {@link StandardCharsets * * @param body The content of the Service Bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into {@link * BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(body.toBytes())); } /** * This constructor provides an easy way to create {@link ServiceBusMessage} with message body as AMQP Data types * {@code SEQUENCE} and {@code VALUE}. * In case of {@code SEQUENCE}, tt support sending and receiving of only one AMQP Sequence at present. * If you are sending message with single byte array or String data, you can also use other constructor. * * @param amqpMessageBody amqp message body. * * @throws NullPointerException if {@code amqpMessageBody} is {@code null}. */ public ServiceBusMessage(AmqpMessageBody amqpMessageBody) { Objects.requireNonNull(amqpMessageBody, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. * @throws IllegalStateException for invalid {@link AmqpMessageBodyType}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); final AmqpMessageBodyType bodyType = receivedMessage.getRawAmqpMessage().getBody().getBodyType(); AmqpMessageBody amqpMessageBody; switch (bodyType) { case DATA: amqpMessageBody = AmqpMessageBody.fromData(receivedMessage.getRawAmqpMessage().getBody() .getFirstData()); break; case SEQUENCE: amqpMessageBody = AmqpMessageBody.fromSequence(receivedMessage.getRawAmqpMessage().getBody() .getSequence()); break; case VALUE: amqpMessageBody = AmqpMessageBody.fromValue(receivedMessage.getRawAmqpMessage().getBody() .getValue()); break; default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); final AmqpMessageProperties receivedProperties = receivedMessage.getRawAmqpMessage().getProperties(); final AmqpMessageProperties newProperties = amqpAnnotatedMessage.getProperties(); newProperties.setMessageId(receivedProperties.getMessageId()); newProperties.setUserId(receivedProperties.getUserId()); newProperties.setTo(receivedProperties.getTo()); newProperties.setSubject(receivedProperties.getSubject()); newProperties.setReplyTo(receivedProperties.getReplyTo()); newProperties.setCorrelationId(receivedProperties.getCorrelationId()); newProperties.setContentType(receivedProperties.getContentType()); newProperties.setContentEncoding(receivedProperties.getContentEncoding()); newProperties.setAbsoluteExpiryTime(receivedProperties.getAbsoluteExpiryTime()); newProperties.setCreationTime(receivedProperties.getCreationTime()); newProperties.setGroupId(receivedProperties.getGroupId()); newProperties.setGroupSequence(receivedProperties.getGroupSequence()); newProperties.setReplyToGroupId(receivedProperties.getReplyToGroupId()); final AmqpMessageHeader receivedHeader = receivedMessage.getRawAmqpMessage().getHeader(); final AmqpMessageHeader newHeader = this.amqpAnnotatedMessage.getHeader(); newHeader.setPriority(receivedHeader.getPriority()); newHeader.setTimeToLive(receivedHeader.getTimeToLive()); newHeader.setDurable(receivedHeader.isDurable()); newHeader.setFirstAcquirer(receivedHeader.isFirstAcquirer()); final Map<String, Object> receivedAnnotations = receivedMessage.getRawAmqpMessage() .getMessageAnnotations(); final Map<String, Object> newAnnotations = this.amqpAnnotatedMessage.getMessageAnnotations(); for (Map.Entry<String, Object> entry : receivedAnnotations.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == LOCKED_UNTIL_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_TIME_UTC_ANNOTATION_NAME) { continue; } newAnnotations.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedDelivery = receivedMessage.getRawAmqpMessage().getDeliveryAnnotations(); final Map<String, Object> newDelivery = this.amqpAnnotatedMessage.getDeliveryAnnotations(); for (Map.Entry<String, Object> entry : receivedDelivery.entrySet()) { newDelivery.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedFooter = receivedMessage.getRawAmqpMessage().getFooter(); final Map<String, Object> newFooter = this.amqpAnnotatedMessage.getFooter(); for (Map.Entry<String, Object> entry : receivedFooter.entrySet()) { newFooter.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedApplicationProperties = receivedMessage.getRawAmqpMessage() .getApplicationProperties(); final Map<String, Object> newApplicationProperties = this.amqpAnnotatedMessage.getApplicationProperties(); for (Map.Entry<String, Object> entry : receivedApplicationProperties.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_REASON_ANNOTATION_NAME) { continue; } newApplicationProperties.put(entry.getKey(), entry.getValue()); } this.context = Context.NONE; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code * getApplicationProperties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides convenience APIs to serialize/deserialize the object.</p> * * <p>If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use * of {@link * consumers who wish to deserialize the binary data.</p> * * @throws IllegalStateException if called for the messages which are not of binary data type. * @return Binary data representing the payload. */ /** * Gets the content type of the message. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * @return The content type of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * * @param contentType RFC2045 Content-Type descriptor of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return The correlation id of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { String correlationId = null; AmqpMessageId amqpCorrelationId = amqpAnnotatedMessage.getProperties().getCorrelationId(); if (amqpCorrelationId != null) { correlationId = amqpCorrelationId.toString(); } return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { AmqpMessageId id = null; if (correlationId != null) { id = new AmqpMessageId(correlationId); } amqpAnnotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the subject for the message. * * <p> * This property enables the application to indicate the purpose of the message to the receiver in a standardized * fashion, similar to an email subject line. The mapped AMQP property is "subject". * </p> * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The application specific subject. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If * enabled, the * <a href="https: * feature identifies and removes second and further submissions of messages with the same {@code messageId}. * </p> * * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { String messageId = null; AmqpMessageId amqpMessageId = amqpAnnotatedMessage.getProperties().getMessageId(); if (amqpMessageId != null) { messageId = amqpMessageId.toString(); } return messageId; } /** * Sets the message id. * * @param messageId The message id to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public ServiceBusMessage setMessageId(String messageId) { checkIdLength("messageId", messageId, MAX_MESSAGE_ID_LENGTH); AmqpMessageId id = null; if (messageId != null) { id = new AmqpMessageId(messageId); } amqpAnnotatedMessage.getProperties().setMessageId(id); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * </p> * * @return The partition key of this message. * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey The partition key of this message. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code partitionKey} is too long or if the {@code partitionKey} does not * match the {@code sessionId}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { checkIdLength("partitionKey", partitionKey, MAX_PARTITION_KEY_LENGTH); checkPartitionKey(partitionKey); amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return The raw AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return amqpAnnotatedMessage; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { String replyTo = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getReplyTo(); if (amqpAddress != null) { replyTo = amqpAddress.toString(); } return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { AmqpAddress replyToAddress = null; if (replyTo != null) { replyToAddress = new AmqpAddress(replyTo); } amqpAnnotatedMessage.getProperties().setReplyTo(replyToAddress); return this; } /** * Gets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @return "To" property value of this message */ public String getTo() { String to = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getTo(); if (amqpAddress != null) { to = amqpAddress.toString(); } return to; } /** * Sets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @param to To property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { AmqpAddress toAddress = null; if (to != null) { toAddress = new AmqpAddress(to); } amqpAnnotatedMessage.getProperties().setTo(toAddress); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the {@link * be set for the reply when sent to the reply entity. * * @return The {@code getReplyToGroupId} property value of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId The ReplyToGroupId property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the session identifier for a session-aware entity. * * <p> * For session-aware entities, this application-defined value specifies the session affiliation of the message. * Messages with the same session identifier are subject to summary locking and enable exact in-order processing and * demultiplexing. For session-unaware entities, this value is ignored. See <a * href="https: * </p> * * @return The session id of the {@link ServiceBusMessage}. * @see <a href="https: */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session identifier for a session-aware entity. * * @param sessionId The session identifier to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code sessionId} is too long or if the {@code sessionId} does not match * the {@code partitionKey}. */ public ServiceBusMessage setSessionId(String sessionId) { checkIdLength("sessionId", sessionId, MAX_SESSION_ID_LENGTH); checkSessionId(sessionId); amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /** * Checks the length of ID fields. * * Some fields within the message will cause a failure in the service without enough context information. */ private void checkIdLength(String fieldName, String value, int maxLength) { if (value != null && value.length() > maxLength) { final String message = String.format("%s cannot be longer than %d characters.", fieldName, maxLength); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkSessionId(String proposedSessionId) { if (proposedSessionId == null) { return; } if (this.getPartitionKey() != null && this.getPartitionKey().compareTo(proposedSessionId) != 0) { final String message = String.format( "sessionId:%s cannot be set to a different value than partitionKey:%s.", proposedSessionId, this.getPartitionKey()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkPartitionKey(String proposedPartitionKey) { if (proposedPartitionKey == null) { return; } if (this.getSessionId() != null && this.getSessionId().compareTo(proposedPartitionKey) != 0) { final String message = String.format( "partitionKey:%s cannot be set to a different value than sessionId:%s.", proposedPartitionKey, this.getSessionId()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } }
@mbhaskar I agree with u, we should have a better definition of the GoneException. Currently, we are kind a little bit abuse the use of it, basically we are using it to wire up the retries, address refresh etc. I think this should be a larger scope discussion about the design etc. As for debugging, this one can be quickly identified through the Rntbd diagnostics. But would a different substatus code help here?
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else if (!this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
error = new GoneException(this.toString(), null, this.args.physicalAddress());
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly() || !this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
Yeah different substatus is definitely a good start to reduce the abuse. Eventually we can also introduce a new exception subclassing GoneException for the client generated scenarios
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else if (!this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
error = new GoneException(this.toString(), null, this.args.physicalAddress());
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly() || !this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
updated.
public void expireRecord(OperationType operationType, boolean requestSent, Class<?> exceptionType) throws URISyntaxException { RntbdRequestArgs requestArgs = new RntbdRequestArgs( RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, ResourceType.Document), new URI("http: ); RntbdRequestTimer requestTimer = new RntbdRequestTimer(5000, 5000); RntbdRequestRecord record = new AsyncRntbdRequestRecord(requestArgs, requestTimer); if (requestSent) { record.setSendingRequestHasStarted(); } record.expire(); try{ record.get(); Assert.fail("RntbdRequestRecord should complete with exception"); } catch (ExecutionException e) { Throwable innerException = e.getCause(); assertThat(innerException).isInstanceOf(exceptionType); } catch (Exception e) { Assert.fail(); } }
Assert.fail("RntbdRequestRecord should complete with exception");
public void expireRecord(OperationType operationType, boolean requestSent, Class<?> exceptionType) throws URISyntaxException { RntbdRequestArgs requestArgs = new RntbdRequestArgs( RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, ResourceType.Document), new URI("http: ); RntbdRequestTimer requestTimer = new RntbdRequestTimer(5000, 5000); RntbdRequestRecord record = new AsyncRntbdRequestRecord(requestArgs, requestTimer); if (requestSent) { record.setSendingRequestHasStarted(); } record.expire(); try{ record.get(); fail("RntbdRequestRecord should complete with exception"); } catch (ExecutionException e) { Throwable innerException = e.getCause(); assertThat(innerException).isInstanceOf(exceptionType); } catch (Exception e) { fail("Wrong exception"); } }
class } }; } @Test(groups = { "unit" }
class } }; } @Test(groups = { "unit" }
updated.
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else if (!this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
error = new GoneException(this.toString(), null, this.args.physicalAddress());
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly() || !this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
Discussed offline, agreed will leave this change out of this PR. Meanwhile, @mbhaskar created this working item to track it : https://github.com/Azure/azure-sdk-for-java/issues/20271 Thanks
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else if (!this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
error = new GoneException(this.toString(), null, this.args.physicalAddress());
public boolean expire() { final CosmosException error; if (this.args.serviceRequest().isReadOnly() || !this.hasSendingRequestStarted()) { error = new GoneException(this.toString(), null, this.args.physicalAddress()); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddress()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
We have guidelines to throw NPE when the input is null and IllegalArgumentException if the input is non-null but invalid. Update other methods in this class as well. https://azure.github.io/azure-sdk/java_introduction.html#java-errors-system-errors
private TableAsyncClient(String tableName, AzureTableImpl implementation, SerializerAdapter serializerAdapter) { this.serializerAdapter = serializerAdapter; try { if (isNullOrEmpty(tableName)) { throw new IllegalArgumentException("'tableName' must be provided to create a TableClient."); } final URI uri = URI.create(implementation.getUrl()); this.accountName = uri.getHost().split("\\.", 2)[0]; this.tableUrl = uri.resolve("/" + tableName).toString(); logger.verbose("Table Service URI: {}", uri); } catch (IllegalArgumentException ex) { throw logger.logExceptionAsError(ex); } this.implementation = implementation; this.tableName = tableName; this.pipeline = implementation.getHttpPipeline(); }
throw new IllegalArgumentException("'tableName' must be provided to create a TableClient.");
private TableAsyncClient(String tableName, AzureTableImpl implementation, SerializerAdapter serializerAdapter) { this.serializerAdapter = serializerAdapter; try { if (tableName == null) { throw new NullPointerException("'tableName' must not be null to create a TableClient."); } if (tableName.isEmpty()) { throw new IllegalArgumentException("'tableName' must not be empty to create a TableClient."); } final URI uri = URI.create(implementation.getUrl()); this.accountName = uri.getHost().split("\\.", 2)[0]; this.tableUrl = uri.resolve("/" + tableName).toString(); logger.verbose("Table Service URI: {}", uri); } catch (NullPointerException | IllegalArgumentException ex) { throw logger.logExceptionAsError(ex); } this.implementation = implementation; this.tableName = tableName; this.pipeline = implementation.getHttpPipeline(); }
class TableAsyncClient { private static final String DELIMITER_CONTINUATION_TOKEN = ";"; private final ClientLogger logger = new ClientLogger(TableAsyncClient.class); private final String tableName; private final AzureTableImpl implementation; private final SerializerAdapter serializerAdapter; private final String accountName; private final String tableUrl; private final HttpPipeline pipeline; TableAsyncClient(String tableName, HttpPipeline pipeline, String serviceUrl, TablesServiceVersion serviceVersion, SerializerAdapter serializerAdapter) { this(tableName, new AzureTableImplBuilder() .url(serviceUrl) .serializerAdapter(serializerAdapter) .pipeline(pipeline) .version(serviceVersion.getVersion()) .buildClient(), serializerAdapter ); } /** * Gets the name of the table. * * @return The name of the table. */ public String getTableName() { return tableName; } /** * Gets the name of the account containing the table. * * @return The name of the account containing the table. */ public String getAccountName() { return accountName; } /** * Gets the absolute URL for this table. * * @return The absolute URL for this table. */ public String getTableUrl() { return tableUrl; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } /** * Gets the REST API version used by this client. * * @return The REST API version used by this client. */ public TablesServiceVersion getApiVersion() { return TablesServiceVersion.fromString(implementation.getVersion()); } /** * Creates a new {@link TableAsyncBatch} object. Batch objects allow you to enqueue multiple create, update, upsert, * and/or delete operations on entities that share the same partition key. When the batch is executed, all of the * operations will be performed as part of a single transaction. As a result, either all operations in the batch * will succeed, or if a failure occurs, all operations in the batch will be rolled back. Each operation in a batch * must operate on a distinct row key. Attempting to add multiple operations to a batch that share the same row key * will cause an exception to be thrown. * * @param partitionKey The partition key shared by all operations in the batch. * * @return An object representing the batch, to which operations can be added. * * @throws IllegalArgumentException If the provided partition key is {@code null} or empty. */ public TableAsyncBatch createBatch(String partitionKey) { if (isNullOrEmpty(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("'partitionKey' cannot be null or empty.")); } return new TableAsyncBatch(partitionKey, this); } AzureTableImpl getImplementation() { return implementation; } /** * Creates the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> create() { return createWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates the table within the Tables service. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createWithResponse() { return withContext(this::createWithResponse); } Mono<Response<Void>> createWithResponse(Context context) { context = context == null ? Context.NONE : context; final TableProperties properties = new TableProperties().setTableName(tableName); try { return implementation.getTables().createWithResponseAsync(properties, null, ResponseFormat.RETURN_NO_CONTENT, null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return An empty reactive result. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> createEntity(TableEntity entity) { return createEntityWithResponse(entity).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createEntityWithResponse(TableEntity entity) { return withContext(context -> createEntityWithResponse(entity, null, context)); } Mono<Response<Void>> createEntityWithResponse(TableEntity entity, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { return implementation.getTables().insertEntityWithResponseAsync(tableName, timeoutInt, null, ResponseFormat.RETURN_NO_CONTENT, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table if it does not exist, or merges the entity with the existing entity otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the provided entity's properties will be merged into the existing entity. * * @param entity The entity to upsert. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity) { return upsertEntityWithResponse(entity, null).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity, UpdateMode updateMode) { return upsertEntityWithResponse(entity, updateMode).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode) { return withContext(context -> upsertEntityWithResponse(entity, updateMode, null, context)); } Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates an existing entity by merging the provided entity with the existing entity. * * @param entity The entity to update. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity) { return updateEntity(entity, null); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode) { return updateEntity(entity, updateMode, false); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return updateEntityWithResponse(entity, updateMode, ifUnchanged).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return withContext(context -> updateEntityWithResponse(entity, updateMode, ifUnchanged, null, context)); } Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } String eTag = ifUnchanged ? entity.getETag() : "*"; EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { return deleteWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the table within the Tables service. * * @return A reactive result containing the response. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<Void>> deleteWithResponse(Context context) { context = context == null ? Context.NONE : context; try { return implementation.getTables().deleteWithResponseAsync(tableName, null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey) { return deleteEntity(partitionKey, rowKey, null); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey, String eTag) { return deleteEntityWithResponse(partitionKey, rowKey, eTag).then(); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return A reactive result containing the response. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag) { return withContext(context -> deleteEntityWithResponse(partitionKey, rowKey, eTag, null, context)); } Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag, Duration timeout, Context context) { context = context == null ? Context.NONE : context; String matchParam = eTag == null ? "*" : eTag; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().deleteEntityWithResponseAsync(tableName, partitionKey, rowKey, matchParam, timeoutInt, null, null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists all entities within the table. * * @return A paged reactive result containing all entities within the table. * * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities() { return listEntities(new ListEntitiesOptions()); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities(ListEntitiesOptions options) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, TableEntity.class)), token -> withContext(context -> listEntitiesNextPage(token, context, options, TableEntity.class))); } /** * Lists all entities within the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing all entities within the table. * * @throws IllegalArgumentException If an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(Class<T> resultType) { return listEntities(new ListEntitiesOptions(), resultType); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed, or if * an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(ListEntitiesOptions options, Class<T> resultType) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, resultType)), token -> withContext(context -> listEntitiesNextPage(token, context, options, resultType))); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesFirstPage(Context context, ListEntitiesOptions options, Class<T> resultType) { return listEntities(null, null, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesNextPage(String token, Context context, ListEntitiesOptions options, Class<T> resultType) { if (token == null) { return Mono.empty(); } String[] split = token.split(DELIMITER_CONTINUATION_TOKEN, 2); if (split.length != 2) { return monoError(logger, new RuntimeException( "Split done incorrectly, must have partition and row key: " + token)); } String nextPartitionKey = split[0]; String nextRowKey = split[1]; return listEntities(nextPartitionKey, nextRowKey, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntities(String nextPartitionKey, String nextRowKey, Context context, ListEntitiesOptions options, Class<T> resultType) { context = context == null ? Context.NONE : context; QueryOptions queryOptions = new QueryOptions() .setFilter(options.getFilter()) .setTop(options.getTop()) .setSelect(options.getSelect()) .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); try { return implementation.getTables().queryEntitiesWithResponseAsync(tableName, null, null, nextPartitionKey, nextRowKey, queryOptions, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .flatMap(response -> { final TableEntityQueryResponse tablesQueryEntityResponse = response.getValue(); if (tablesQueryEntityResponse == null) { return Mono.empty(); } final List<Map<String, Object>> entityResponseValue = tablesQueryEntityResponse.getValue(); if (entityResponseValue == null) { return Mono.empty(); } final List<T> entities = entityResponseValue.stream() .map(ModelHelper::createEntity) .map(e -> EntityHelper.convertToSubclass(e, resultType, logger)) .collect(Collectors.toList()); return Mono.just(new EntityPaged<>(response, entities, response.getDeserializedHeaders().getXMsContinuationNextPartitionKey(), response.getDeserializedHeaders().getXMsContinuationNextRowKey())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private static class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey) { return getEntityWithResponse(partitionKey, rowKey, null).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey, String select) { return getEntityWithResponse(partitionKey, rowKey, select).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if an * instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, null, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, String select, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, select, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TableEntity>> getEntityWithResponse(String partitionKey, String rowKey, String select) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, TableEntity.class, null, context)); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, resultType, null, context)); } <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType, Duration timeout, Context context) { Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); QueryOptions queryOptions = new QueryOptions() .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); if (select != null) { queryOptions.setSelect(select); } if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().queryEntityWithPartitionAndRowKeyWithResponseAsync(tableName, partitionKey, rowKey, timeoutInt, null, queryOptions, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .handle((response, sink) -> { final Map<String, Object> matchingEntity = response.getValue(); if (matchingEntity == null || matchingEntity.isEmpty()) { logger.info("There was no matching entity. Table: {}, partition key: {}, row key: {}.", tableName, partitionKey, rowKey); sink.complete(); return; } final TableEntity entity = ModelHelper.createEntity(matchingEntity); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), EntityHelper.convertToSubclass(entity, resultType, logger))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class TableAsyncClient { private static final String DELIMITER_CONTINUATION_TOKEN = ";"; private final ClientLogger logger = new ClientLogger(TableAsyncClient.class); private final String tableName; private final AzureTableImpl implementation; private final SerializerAdapter serializerAdapter; private final String accountName; private final String tableUrl; private final HttpPipeline pipeline; TableAsyncClient(String tableName, HttpPipeline pipeline, String serviceUrl, TablesServiceVersion serviceVersion, SerializerAdapter serializerAdapter) { this(tableName, new AzureTableImplBuilder() .url(serviceUrl) .serializerAdapter(serializerAdapter) .pipeline(pipeline) .version(serviceVersion.getVersion()) .buildClient(), serializerAdapter ); } /** * Gets the name of the table. * * @return The name of the table. */ public String getTableName() { return tableName; } /** * Gets the name of the account containing the table. * * @return The name of the account containing the table. */ public String getAccountName() { return accountName; } /** * Gets the absolute URL for this table. * * @return The absolute URL for this table. */ public String getTableUrl() { return tableUrl; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } /** * Gets the REST API version used by this client. * * @return The REST API version used by this client. */ public TablesServiceVersion getApiVersion() { return TablesServiceVersion.fromString(implementation.getVersion()); } /** * Creates a new {@link TableAsyncBatch} object. Batch objects allow you to enqueue multiple create, update, upsert, * and/or delete operations on entities that share the same partition key. When the batch is executed, all of the * operations will be performed as part of a single transaction. As a result, either all operations in the batch * will succeed, or if a failure occurs, all operations in the batch will be rolled back. Each operation in a batch * must operate on a distinct row key. Attempting to add multiple operations to a batch that share the same row key * will cause an exception to be thrown. * * @param partitionKey The partition key shared by all operations in the batch. * * @return An object representing the batch, to which operations can be added. * * @throws IllegalArgumentException If the provided partition key is {@code null} or empty. */ public TableAsyncBatch createBatch(String partitionKey) { if (isNullOrEmpty(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("'partitionKey' cannot be null or empty.")); } return new TableAsyncBatch(partitionKey, this); } AzureTableImpl getImplementation() { return implementation; } /** * Creates the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> create() { return createWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates the table within the Tables service. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createWithResponse() { return withContext(this::createWithResponse); } Mono<Response<Void>> createWithResponse(Context context) { context = context == null ? Context.NONE : context; final TableProperties properties = new TableProperties().setTableName(tableName); try { return implementation.getTables().createWithResponseAsync(properties, null, ResponseFormat.RETURN_NO_CONTENT, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return An empty reactive result. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> createEntity(TableEntity entity) { return createEntityWithResponse(entity).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createEntityWithResponse(TableEntity entity) { return withContext(context -> createEntityWithResponse(entity, null, context)); } Mono<Response<Void>> createEntityWithResponse(TableEntity entity, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { return implementation.getTables().insertEntityWithResponseAsync(tableName, timeoutInt, null, ResponseFormat.RETURN_NO_CONTENT, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table if it does not exist, or merges the entity with the existing entity otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the provided entity's properties will be merged into the existing entity. * * @param entity The entity to upsert. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity) { return upsertEntityWithResponse(entity, null).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity, UpdateMode updateMode) { return upsertEntityWithResponse(entity, updateMode).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode) { return withContext(context -> upsertEntityWithResponse(entity, updateMode, null, context)); } Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates an existing entity by merging the provided entity with the existing entity. * * @param entity The entity to update. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity) { return updateEntity(entity, null); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode) { return updateEntity(entity, updateMode, false); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return updateEntityWithResponse(entity, updateMode, ifUnchanged).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return withContext(context -> updateEntityWithResponse(entity, updateMode, ifUnchanged, null, context)); } Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } String eTag = ifUnchanged ? entity.getETag() : "*"; EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { return deleteWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the table within the Tables service. * * @return A reactive result containing the response. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<Void>> deleteWithResponse(Context context) { context = context == null ? Context.NONE : context; try { return implementation.getTables().deleteWithResponseAsync(tableName, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey) { return deleteEntity(partitionKey, rowKey, null); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey, String eTag) { return deleteEntityWithResponse(partitionKey, rowKey, eTag).then(); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return A reactive result containing the response. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag) { return withContext(context -> deleteEntityWithResponse(partitionKey, rowKey, eTag, null, context)); } Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag, Duration timeout, Context context) { context = context == null ? Context.NONE : context; String matchParam = eTag == null ? "*" : eTag; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().deleteEntityWithResponseAsync(tableName, partitionKey, rowKey, matchParam, timeoutInt, null, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists all entities within the table. * * @return A paged reactive result containing all entities within the table. * * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities() { return listEntities(new ListEntitiesOptions()); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities(ListEntitiesOptions options) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, TableEntity.class)), token -> withContext(context -> listEntitiesNextPage(token, context, options, TableEntity.class))); } /** * Lists all entities within the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing all entities within the table. * * @throws IllegalArgumentException If an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(Class<T> resultType) { return listEntities(new ListEntitiesOptions(), resultType); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed, or if * an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(ListEntitiesOptions options, Class<T> resultType) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, resultType)), token -> withContext(context -> listEntitiesNextPage(token, context, options, resultType))); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesFirstPage(Context context, ListEntitiesOptions options, Class<T> resultType) { return listEntities(null, null, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesNextPage(String token, Context context, ListEntitiesOptions options, Class<T> resultType) { if (token == null) { return Mono.empty(); } String[] split = token.split(DELIMITER_CONTINUATION_TOKEN, 2); if (split.length != 2) { return monoError(logger, new RuntimeException( "Split done incorrectly, must have partition and row key: " + token)); } String nextPartitionKey = split[0]; String nextRowKey = split[1]; return listEntities(nextPartitionKey, nextRowKey, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntities(String nextPartitionKey, String nextRowKey, Context context, ListEntitiesOptions options, Class<T> resultType) { context = context == null ? Context.NONE : context; QueryOptions queryOptions = new QueryOptions() .setFilter(options.getFilter()) .setTop(options.getTop()) .setSelect(options.getSelect()) .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); try { return implementation.getTables().queryEntitiesWithResponseAsync(tableName, null, null, nextPartitionKey, nextRowKey, queryOptions, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .flatMap(response -> { final TableEntityQueryResponse tablesQueryEntityResponse = response.getValue(); if (tablesQueryEntityResponse == null) { return Mono.empty(); } final List<Map<String, Object>> entityResponseValue = tablesQueryEntityResponse.getValue(); if (entityResponseValue == null) { return Mono.empty(); } final List<T> entities = entityResponseValue.stream() .map(ModelHelper::createEntity) .map(e -> EntityHelper.convertToSubclass(e, resultType, logger)) .collect(Collectors.toList()); return Mono.just(new EntityPaged<>(response, entities, response.getDeserializedHeaders().getXMsContinuationNextPartitionKey(), response.getDeserializedHeaders().getXMsContinuationNextRowKey())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private static class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey) { return getEntityWithResponse(partitionKey, rowKey, null).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey, String select) { return getEntityWithResponse(partitionKey, rowKey, select).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if an * instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, null, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, String select, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, select, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TableEntity>> getEntityWithResponse(String partitionKey, String rowKey, String select) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, TableEntity.class, null, context)); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, resultType, null, context)); } <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType, Duration timeout, Context context) { Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); QueryOptions queryOptions = new QueryOptions() .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); if (select != null) { queryOptions.setSelect(select); } if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().queryEntityWithPartitionAndRowKeyWithResponseAsync(tableName, partitionKey, rowKey, timeoutInt, null, queryOptions, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .handle((response, sink) -> { final Map<String, Object> matchingEntity = response.getValue(); if (matchingEntity == null || matchingEntity.isEmpty()) { logger.info("There was no matching entity. Table: {}, partition key: {}, row key: {}.", tableName, partitionKey, rowKey); sink.complete(); return; } final TableEntity entity = ModelHelper.createEntity(matchingEntity); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), EntityHelper.convertToSubclass(entity, resultType, logger))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Move this into a method instead of repeating it in all `doOnError`.
Mono<Response<Void>> createEntityWithResponse(TableEntity entity, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { return implementation.getTables().insertEntityWithResponseAsync(tableName, timeoutInt, null, ResponseFormat.RETURN_NO_CONTENT, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
}
return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { return implementation.getTables().insertEntityWithResponseAsync(tableName, timeoutInt, null, ResponseFormat.RETURN_NO_CONTENT, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); }
class TableAsyncClient { private static final String DELIMITER_CONTINUATION_TOKEN = ";"; private final ClientLogger logger = new ClientLogger(TableAsyncClient.class); private final String tableName; private final AzureTableImpl implementation; private final SerializerAdapter serializerAdapter; private final String accountName; private final String tableUrl; private final HttpPipeline pipeline; private TableAsyncClient(String tableName, AzureTableImpl implementation, SerializerAdapter serializerAdapter) { this.serializerAdapter = serializerAdapter; try { if (isNullOrEmpty(tableName)) { throw new IllegalArgumentException("'tableName' must be provided to create a TableClient."); } final URI uri = URI.create(implementation.getUrl()); this.accountName = uri.getHost().split("\\.", 2)[0]; this.tableUrl = uri.resolve("/" + tableName).toString(); logger.verbose("Table Service URI: {}", uri); } catch (IllegalArgumentException ex) { throw logger.logExceptionAsError(ex); } this.implementation = implementation; this.tableName = tableName; this.pipeline = implementation.getHttpPipeline(); } TableAsyncClient(String tableName, HttpPipeline pipeline, String serviceUrl, TablesServiceVersion serviceVersion, SerializerAdapter serializerAdapter) { this(tableName, new AzureTableImplBuilder() .url(serviceUrl) .serializerAdapter(serializerAdapter) .pipeline(pipeline) .version(serviceVersion.getVersion()) .buildClient(), serializerAdapter ); } /** * Gets the name of the table. * * @return The name of the table. */ public String getTableName() { return tableName; } /** * Gets the name of the account containing the table. * * @return The name of the account containing the table. */ public String getAccountName() { return accountName; } /** * Gets the absolute URL for this table. * * @return The absolute URL for this table. */ public String getTableUrl() { return tableUrl; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } /** * Gets the REST API version used by this client. * * @return The REST API version used by this client. */ public TablesServiceVersion getApiVersion() { return TablesServiceVersion.fromString(implementation.getVersion()); } /** * Creates a new {@link TableAsyncBatch} object. Batch objects allow you to enqueue multiple create, update, upsert, * and/or delete operations on entities that share the same partition key. When the batch is executed, all of the * operations will be performed as part of a single transaction. As a result, either all operations in the batch * will succeed, or if a failure occurs, all operations in the batch will be rolled back. Each operation in a batch * must operate on a distinct row key. Attempting to add multiple operations to a batch that share the same row key * will cause an exception to be thrown. * * @param partitionKey The partition key shared by all operations in the batch. * * @return An object representing the batch, to which operations can be added. * * @throws IllegalArgumentException If the provided partition key is {@code null} or empty. */ public TableAsyncBatch createBatch(String partitionKey) { if (isNullOrEmpty(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("'partitionKey' cannot be null or empty.")); } return new TableAsyncBatch(partitionKey, this); } AzureTableImpl getImplementation() { return implementation; } /** * Creates the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> create() { return createWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates the table within the Tables service. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createWithResponse() { return withContext(this::createWithResponse); } Mono<Response<Void>> createWithResponse(Context context) { context = context == null ? Context.NONE : context; final TableProperties properties = new TableProperties().setTableName(tableName); try { return implementation.getTables().createWithResponseAsync(properties, null, ResponseFormat.RETURN_NO_CONTENT, null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return An empty reactive result. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> createEntity(TableEntity entity) { return createEntityWithResponse(entity).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createEntityWithResponse(TableEntity entity) { return withContext(context -> createEntityWithResponse(entity, null, context)); } Mono<Response<Void>> createEntityWithResponse(TableEntity entity, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table if it does not exist, or merges the entity with the existing entity otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the provided entity's properties will be merged into the existing entity. * * @param entity The entity to upsert. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity) { return upsertEntityWithResponse(entity, null).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity, UpdateMode updateMode) { return upsertEntityWithResponse(entity, updateMode).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode) { return withContext(context -> upsertEntityWithResponse(entity, updateMode, null, context)); } Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates an existing entity by merging the provided entity with the existing entity. * * @param entity The entity to update. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity) { return updateEntity(entity, null); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode) { return updateEntity(entity, updateMode, false); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return updateEntityWithResponse(entity, updateMode, ifUnchanged).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return withContext(context -> updateEntityWithResponse(entity, updateMode, ifUnchanged, null, context)); } Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } String eTag = ifUnchanged ? entity.getETag() : "*"; EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { return deleteWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the table within the Tables service. * * @return A reactive result containing the response. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<Void>> deleteWithResponse(Context context) { context = context == null ? Context.NONE : context; try { return implementation.getTables().deleteWithResponseAsync(tableName, null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey) { return deleteEntity(partitionKey, rowKey, null); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey, String eTag) { return deleteEntityWithResponse(partitionKey, rowKey, eTag).then(); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return A reactive result containing the response. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag) { return withContext(context -> deleteEntityWithResponse(partitionKey, rowKey, eTag, null, context)); } Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag, Duration timeout, Context context) { context = context == null ? Context.NONE : context; String matchParam = eTag == null ? "*" : eTag; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().deleteEntityWithResponseAsync(tableName, partitionKey, rowKey, matchParam, timeoutInt, null, null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists all entities within the table. * * @return A paged reactive result containing all entities within the table. * * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities() { return listEntities(new ListEntitiesOptions()); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities(ListEntitiesOptions options) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, TableEntity.class)), token -> withContext(context -> listEntitiesNextPage(token, context, options, TableEntity.class))); } /** * Lists all entities within the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing all entities within the table. * * @throws IllegalArgumentException If an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(Class<T> resultType) { return listEntities(new ListEntitiesOptions(), resultType); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed, or if * an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(ListEntitiesOptions options, Class<T> resultType) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, resultType)), token -> withContext(context -> listEntitiesNextPage(token, context, options, resultType))); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesFirstPage(Context context, ListEntitiesOptions options, Class<T> resultType) { return listEntities(null, null, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesNextPage(String token, Context context, ListEntitiesOptions options, Class<T> resultType) { if (token == null) { return Mono.empty(); } String[] split = token.split(DELIMITER_CONTINUATION_TOKEN, 2); if (split.length != 2) { return monoError(logger, new RuntimeException( "Split done incorrectly, must have partition and row key: " + token)); } String nextPartitionKey = split[0]; String nextRowKey = split[1]; return listEntities(nextPartitionKey, nextRowKey, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntities(String nextPartitionKey, String nextRowKey, Context context, ListEntitiesOptions options, Class<T> resultType) { context = context == null ? Context.NONE : context; QueryOptions queryOptions = new QueryOptions() .setFilter(options.getFilter()) .setTop(options.getTop()) .setSelect(options.getSelect()) .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); try { return implementation.getTables().queryEntitiesWithResponseAsync(tableName, null, null, nextPartitionKey, nextRowKey, queryOptions, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .flatMap(response -> { final TableEntityQueryResponse tablesQueryEntityResponse = response.getValue(); if (tablesQueryEntityResponse == null) { return Mono.empty(); } final List<Map<String, Object>> entityResponseValue = tablesQueryEntityResponse.getValue(); if (entityResponseValue == null) { return Mono.empty(); } final List<T> entities = entityResponseValue.stream() .map(ModelHelper::createEntity) .map(e -> EntityHelper.convertToSubclass(e, resultType, logger)) .collect(Collectors.toList()); return Mono.just(new EntityPaged<>(response, entities, response.getDeserializedHeaders().getXMsContinuationNextPartitionKey(), response.getDeserializedHeaders().getXMsContinuationNextRowKey())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private static class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey) { return getEntityWithResponse(partitionKey, rowKey, null).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey, String select) { return getEntityWithResponse(partitionKey, rowKey, select).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if an * instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, null, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, String select, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, select, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TableEntity>> getEntityWithResponse(String partitionKey, String rowKey, String select) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, TableEntity.class, null, context)); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, resultType, null, context)); } <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType, Duration timeout, Context context) { Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); QueryOptions queryOptions = new QueryOptions() .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); if (select != null) { queryOptions.setSelect(select); } if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().queryEntityWithPartitionAndRowKeyWithResponseAsync(tableName, partitionKey, rowKey, timeoutInt, null, queryOptions, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .handle((response, sink) -> { final Map<String, Object> matchingEntity = response.getValue(); if (matchingEntity == null || matchingEntity.isEmpty()) { logger.info("There was no matching entity. Table: {}, partition key: {}, row key: {}.", tableName, partitionKey, rowKey); sink.complete(); return; } final TableEntity entity = ModelHelper.createEntity(matchingEntity); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), EntityHelper.convertToSubclass(entity, resultType, logger))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class TableAsyncClient { private static final String DELIMITER_CONTINUATION_TOKEN = ";"; private final ClientLogger logger = new ClientLogger(TableAsyncClient.class); private final String tableName; private final AzureTableImpl implementation; private final SerializerAdapter serializerAdapter; private final String accountName; private final String tableUrl; private final HttpPipeline pipeline; private TableAsyncClient(String tableName, AzureTableImpl implementation, SerializerAdapter serializerAdapter) { this.serializerAdapter = serializerAdapter; try { if (tableName == null) { throw new NullPointerException("'tableName' must not be null to create a TableClient."); } if (tableName.isEmpty()) { throw new IllegalArgumentException("'tableName' must not be empty to create a TableClient."); } final URI uri = URI.create(implementation.getUrl()); this.accountName = uri.getHost().split("\\.", 2)[0]; this.tableUrl = uri.resolve("/" + tableName).toString(); logger.verbose("Table Service URI: {}", uri); } catch (NullPointerException | IllegalArgumentException ex) { throw logger.logExceptionAsError(ex); } this.implementation = implementation; this.tableName = tableName; this.pipeline = implementation.getHttpPipeline(); } TableAsyncClient(String tableName, HttpPipeline pipeline, String serviceUrl, TablesServiceVersion serviceVersion, SerializerAdapter serializerAdapter) { this(tableName, new AzureTableImplBuilder() .url(serviceUrl) .serializerAdapter(serializerAdapter) .pipeline(pipeline) .version(serviceVersion.getVersion()) .buildClient(), serializerAdapter ); } /** * Gets the name of the table. * * @return The name of the table. */ public String getTableName() { return tableName; } /** * Gets the name of the account containing the table. * * @return The name of the account containing the table. */ public String getAccountName() { return accountName; } /** * Gets the absolute URL for this table. * * @return The absolute URL for this table. */ public String getTableUrl() { return tableUrl; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } /** * Gets the REST API version used by this client. * * @return The REST API version used by this client. */ public TablesServiceVersion getApiVersion() { return TablesServiceVersion.fromString(implementation.getVersion()); } /** * Creates a new {@link TableAsyncBatch} object. Batch objects allow you to enqueue multiple create, update, upsert, * and/or delete operations on entities that share the same partition key. When the batch is executed, all of the * operations will be performed as part of a single transaction. As a result, either all operations in the batch * will succeed, or if a failure occurs, all operations in the batch will be rolled back. Each operation in a batch * must operate on a distinct row key. Attempting to add multiple operations to a batch that share the same row key * will cause an exception to be thrown. * * @param partitionKey The partition key shared by all operations in the batch. * * @return An object representing the batch, to which operations can be added. * * @throws IllegalArgumentException If the provided partition key is {@code null} or empty. */ public TableAsyncBatch createBatch(String partitionKey) { if (isNullOrEmpty(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("'partitionKey' cannot be null or empty.")); } return new TableAsyncBatch(partitionKey, this); } AzureTableImpl getImplementation() { return implementation; } /** * Creates the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> create() { return createWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates the table within the Tables service. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createWithResponse() { return withContext(this::createWithResponse); } Mono<Response<Void>> createWithResponse(Context context) { context = context == null ? Context.NONE : context; final TableProperties properties = new TableProperties().setTableName(tableName); try { return implementation.getTables().createWithResponseAsync(properties, null, ResponseFormat.RETURN_NO_CONTENT, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return An empty reactive result. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> createEntity(TableEntity entity) { return createEntityWithResponse(entity).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createEntityWithResponse(TableEntity entity) { return withContext(context -> createEntityWithResponse(entity, null, context)); } Mono<Response<Void>> createEntityWithResponse(TableEntity entity, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table if it does not exist, or merges the entity with the existing entity otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the provided entity's properties will be merged into the existing entity. * * @param entity The entity to upsert. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity) { return upsertEntityWithResponse(entity, null).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity, UpdateMode updateMode) { return upsertEntityWithResponse(entity, updateMode).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode) { return withContext(context -> upsertEntityWithResponse(entity, updateMode, null, context)); } Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates an existing entity by merging the provided entity with the existing entity. * * @param entity The entity to update. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity) { return updateEntity(entity, null); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode) { return updateEntity(entity, updateMode, false); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return updateEntityWithResponse(entity, updateMode, ifUnchanged).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return withContext(context -> updateEntityWithResponse(entity, updateMode, ifUnchanged, null, context)); } Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } String eTag = ifUnchanged ? entity.getETag() : "*"; EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { return deleteWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the table within the Tables service. * * @return A reactive result containing the response. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<Void>> deleteWithResponse(Context context) { context = context == null ? Context.NONE : context; try { return implementation.getTables().deleteWithResponseAsync(tableName, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey) { return deleteEntity(partitionKey, rowKey, null); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey, String eTag) { return deleteEntityWithResponse(partitionKey, rowKey, eTag).then(); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return A reactive result containing the response. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag) { return withContext(context -> deleteEntityWithResponse(partitionKey, rowKey, eTag, null, context)); } Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag, Duration timeout, Context context) { context = context == null ? Context.NONE : context; String matchParam = eTag == null ? "*" : eTag; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().deleteEntityWithResponseAsync(tableName, partitionKey, rowKey, matchParam, timeoutInt, null, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists all entities within the table. * * @return A paged reactive result containing all entities within the table. * * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities() { return listEntities(new ListEntitiesOptions()); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities(ListEntitiesOptions options) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, TableEntity.class)), token -> withContext(context -> listEntitiesNextPage(token, context, options, TableEntity.class))); } /** * Lists all entities within the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing all entities within the table. * * @throws IllegalArgumentException If an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(Class<T> resultType) { return listEntities(new ListEntitiesOptions(), resultType); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed, or if * an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(ListEntitiesOptions options, Class<T> resultType) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, resultType)), token -> withContext(context -> listEntitiesNextPage(token, context, options, resultType))); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesFirstPage(Context context, ListEntitiesOptions options, Class<T> resultType) { return listEntities(null, null, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesNextPage(String token, Context context, ListEntitiesOptions options, Class<T> resultType) { if (token == null) { return Mono.empty(); } String[] split = token.split(DELIMITER_CONTINUATION_TOKEN, 2); if (split.length != 2) { return monoError(logger, new RuntimeException( "Split done incorrectly, must have partition and row key: " + token)); } String nextPartitionKey = split[0]; String nextRowKey = split[1]; return listEntities(nextPartitionKey, nextRowKey, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntities(String nextPartitionKey, String nextRowKey, Context context, ListEntitiesOptions options, Class<T> resultType) { context = context == null ? Context.NONE : context; QueryOptions queryOptions = new QueryOptions() .setFilter(options.getFilter()) .setTop(options.getTop()) .setSelect(options.getSelect()) .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); try { return implementation.getTables().queryEntitiesWithResponseAsync(tableName, null, null, nextPartitionKey, nextRowKey, queryOptions, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .flatMap(response -> { final TableEntityQueryResponse tablesQueryEntityResponse = response.getValue(); if (tablesQueryEntityResponse == null) { return Mono.empty(); } final List<Map<String, Object>> entityResponseValue = tablesQueryEntityResponse.getValue(); if (entityResponseValue == null) { return Mono.empty(); } final List<T> entities = entityResponseValue.stream() .map(ModelHelper::createEntity) .map(e -> EntityHelper.convertToSubclass(e, resultType, logger)) .collect(Collectors.toList()); return Mono.just(new EntityPaged<>(response, entities, response.getDeserializedHeaders().getXMsContinuationNextPartitionKey(), response.getDeserializedHeaders().getXMsContinuationNextRowKey())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private static class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey) { return getEntityWithResponse(partitionKey, rowKey, null).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey, String select) { return getEntityWithResponse(partitionKey, rowKey, select).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if an * instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, null, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, String select, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, select, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TableEntity>> getEntityWithResponse(String partitionKey, String rowKey, String select) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, TableEntity.class, null, context)); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, resultType, null, context)); } <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType, Duration timeout, Context context) { Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); QueryOptions queryOptions = new QueryOptions() .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); if (select != null) { queryOptions.setSelect(select); } if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().queryEntityWithPartitionAndRowKeyWithResponseAsync(tableName, partitionKey, rowKey, timeoutInt, null, queryOptions, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .handle((response, sink) -> { final Map<String, Object> matchingEntity = response.getValue(); if (matchingEntity == null || matchingEntity.isEmpty()) { logger.info("There was no matching entity. Table: {}, partition key: {}, row key: {}.", tableName, partitionKey, rowKey); sink.complete(); return; } final TableEntity entity = ModelHelper.createEntity(matchingEntity); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), EntityHelper.convertToSubclass(entity, resultType, logger))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Use `onErrorMap` instead of `doOnError` .
Mono<Response<Void>> createWithResponse(Context context) { context = context == null ? Context.NONE : context; final TableProperties properties = new TableProperties().setTableName(tableName); try { return implementation.getTables().createWithResponseAsync(properties, null, ResponseFormat.RETURN_NO_CONTENT, null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
.doOnError(throwable -> {
new TableProperties().setTableName(tableName); try { return implementation.getTables().createWithResponseAsync(properties, null, ResponseFormat.RETURN_NO_CONTENT, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response, null)); }
class TableAsyncClient { private static final String DELIMITER_CONTINUATION_TOKEN = ";"; private final ClientLogger logger = new ClientLogger(TableAsyncClient.class); private final String tableName; private final AzureTableImpl implementation; private final SerializerAdapter serializerAdapter; private final String accountName; private final String tableUrl; private final HttpPipeline pipeline; private TableAsyncClient(String tableName, AzureTableImpl implementation, SerializerAdapter serializerAdapter) { this.serializerAdapter = serializerAdapter; try { if (isNullOrEmpty(tableName)) { throw new IllegalArgumentException("'tableName' must be provided to create a TableClient."); } final URI uri = URI.create(implementation.getUrl()); this.accountName = uri.getHost().split("\\.", 2)[0]; this.tableUrl = uri.resolve("/" + tableName).toString(); logger.verbose("Table Service URI: {}", uri); } catch (IllegalArgumentException ex) { throw logger.logExceptionAsError(ex); } this.implementation = implementation; this.tableName = tableName; this.pipeline = implementation.getHttpPipeline(); } TableAsyncClient(String tableName, HttpPipeline pipeline, String serviceUrl, TablesServiceVersion serviceVersion, SerializerAdapter serializerAdapter) { this(tableName, new AzureTableImplBuilder() .url(serviceUrl) .serializerAdapter(serializerAdapter) .pipeline(pipeline) .version(serviceVersion.getVersion()) .buildClient(), serializerAdapter ); } /** * Gets the name of the table. * * @return The name of the table. */ public String getTableName() { return tableName; } /** * Gets the name of the account containing the table. * * @return The name of the account containing the table. */ public String getAccountName() { return accountName; } /** * Gets the absolute URL for this table. * * @return The absolute URL for this table. */ public String getTableUrl() { return tableUrl; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } /** * Gets the REST API version used by this client. * * @return The REST API version used by this client. */ public TablesServiceVersion getApiVersion() { return TablesServiceVersion.fromString(implementation.getVersion()); } /** * Creates a new {@link TableAsyncBatch} object. Batch objects allow you to enqueue multiple create, update, upsert, * and/or delete operations on entities that share the same partition key. When the batch is executed, all of the * operations will be performed as part of a single transaction. As a result, either all operations in the batch * will succeed, or if a failure occurs, all operations in the batch will be rolled back. Each operation in a batch * must operate on a distinct row key. Attempting to add multiple operations to a batch that share the same row key * will cause an exception to be thrown. * * @param partitionKey The partition key shared by all operations in the batch. * * @return An object representing the batch, to which operations can be added. * * @throws IllegalArgumentException If the provided partition key is {@code null} or empty. */ public TableAsyncBatch createBatch(String partitionKey) { if (isNullOrEmpty(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("'partitionKey' cannot be null or empty.")); } return new TableAsyncBatch(partitionKey, this); } AzureTableImpl getImplementation() { return implementation; } /** * Creates the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> create() { return createWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates the table within the Tables service. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createWithResponse() { return withContext(this::createWithResponse); } Mono<Response<Void>> createWithResponse(Context context) { context = context == null ? Context.NONE : context; final TableProperties properties = catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return An empty reactive result. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> createEntity(TableEntity entity) { return createEntityWithResponse(entity).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createEntityWithResponse(TableEntity entity) { return withContext(context -> createEntityWithResponse(entity, null, context)); } Mono<Response<Void>> createEntityWithResponse(TableEntity entity, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { return implementation.getTables().insertEntityWithResponseAsync(tableName, timeoutInt, null, ResponseFormat.RETURN_NO_CONTENT, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table if it does not exist, or merges the entity with the existing entity otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the provided entity's properties will be merged into the existing entity. * * @param entity The entity to upsert. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity) { return upsertEntityWithResponse(entity, null).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity, UpdateMode updateMode) { return upsertEntityWithResponse(entity, updateMode).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode) { return withContext(context -> upsertEntityWithResponse(entity, updateMode, null, context)); } Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates an existing entity by merging the provided entity with the existing entity. * * @param entity The entity to update. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity) { return updateEntity(entity, null); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode) { return updateEntity(entity, updateMode, false); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return updateEntityWithResponse(entity, updateMode, ifUnchanged).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return withContext(context -> updateEntityWithResponse(entity, updateMode, ifUnchanged, null, context)); } Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } String eTag = ifUnchanged ? entity.getETag() : "*"; EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { return deleteWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the table within the Tables service. * * @return A reactive result containing the response. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<Void>> deleteWithResponse(Context context) { context = context == null ? Context.NONE : context; try { return implementation.getTables().deleteWithResponseAsync(tableName, null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey) { return deleteEntity(partitionKey, rowKey, null); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey, String eTag) { return deleteEntityWithResponse(partitionKey, rowKey, eTag).then(); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return A reactive result containing the response. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag) { return withContext(context -> deleteEntityWithResponse(partitionKey, rowKey, eTag, null, context)); } Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag, Duration timeout, Context context) { context = context == null ? Context.NONE : context; String matchParam = eTag == null ? "*" : eTag; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().deleteEntityWithResponseAsync(tableName, partitionKey, rowKey, matchParam, timeoutInt, null, null, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists all entities within the table. * * @return A paged reactive result containing all entities within the table. * * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities() { return listEntities(new ListEntitiesOptions()); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities(ListEntitiesOptions options) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, TableEntity.class)), token -> withContext(context -> listEntitiesNextPage(token, context, options, TableEntity.class))); } /** * Lists all entities within the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing all entities within the table. * * @throws IllegalArgumentException If an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(Class<T> resultType) { return listEntities(new ListEntitiesOptions(), resultType); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed, or if * an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(ListEntitiesOptions options, Class<T> resultType) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, resultType)), token -> withContext(context -> listEntitiesNextPage(token, context, options, resultType))); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesFirstPage(Context context, ListEntitiesOptions options, Class<T> resultType) { return listEntities(null, null, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesNextPage(String token, Context context, ListEntitiesOptions options, Class<T> resultType) { if (token == null) { return Mono.empty(); } String[] split = token.split(DELIMITER_CONTINUATION_TOKEN, 2); if (split.length != 2) { return monoError(logger, new RuntimeException( "Split done incorrectly, must have partition and row key: " + token)); } String nextPartitionKey = split[0]; String nextRowKey = split[1]; return listEntities(nextPartitionKey, nextRowKey, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntities(String nextPartitionKey, String nextRowKey, Context context, ListEntitiesOptions options, Class<T> resultType) { context = context == null ? Context.NONE : context; QueryOptions queryOptions = new QueryOptions() .setFilter(options.getFilter()) .setTop(options.getTop()) .setSelect(options.getSelect()) .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); try { return implementation.getTables().queryEntitiesWithResponseAsync(tableName, null, null, nextPartitionKey, nextRowKey, queryOptions, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .flatMap(response -> { final TableEntityQueryResponse tablesQueryEntityResponse = response.getValue(); if (tablesQueryEntityResponse == null) { return Mono.empty(); } final List<Map<String, Object>> entityResponseValue = tablesQueryEntityResponse.getValue(); if (entityResponseValue == null) { return Mono.empty(); } final List<T> entities = entityResponseValue.stream() .map(ModelHelper::createEntity) .map(e -> EntityHelper.convertToSubclass(e, resultType, logger)) .collect(Collectors.toList()); return Mono.just(new EntityPaged<>(response, entities, response.getDeserializedHeaders().getXMsContinuationNextPartitionKey(), response.getDeserializedHeaders().getXMsContinuationNextRowKey())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private static class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey) { return getEntityWithResponse(partitionKey, rowKey, null).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey, String select) { return getEntityWithResponse(partitionKey, rowKey, select).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if an * instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, null, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, String select, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, select, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TableEntity>> getEntityWithResponse(String partitionKey, String rowKey, String select) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, TableEntity.class, null, context)); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, resultType, null, context)); } <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType, Duration timeout, Context context) { Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); QueryOptions queryOptions = new QueryOptions() .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); if (select != null) { queryOptions.setSelect(select); } if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().queryEntityWithPartitionAndRowKeyWithResponseAsync(tableName, partitionKey, rowKey, timeoutInt, null, queryOptions, context) .doOnError(throwable -> { if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { throw toTableServiceErrorException( (com.azure.data.tables.implementation.models.TableServiceErrorException) throwable); } }) .handle((response, sink) -> { final Map<String, Object> matchingEntity = response.getValue(); if (matchingEntity == null || matchingEntity.isEmpty()) { logger.info("There was no matching entity. Table: {}, partition key: {}, row key: {}.", tableName, partitionKey, rowKey); sink.complete(); return; } final TableEntity entity = ModelHelper.createEntity(matchingEntity); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), EntityHelper.convertToSubclass(entity, resultType, logger))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class TableAsyncClient { private static final String DELIMITER_CONTINUATION_TOKEN = ";"; private final ClientLogger logger = new ClientLogger(TableAsyncClient.class); private final String tableName; private final AzureTableImpl implementation; private final SerializerAdapter serializerAdapter; private final String accountName; private final String tableUrl; private final HttpPipeline pipeline; private TableAsyncClient(String tableName, AzureTableImpl implementation, SerializerAdapter serializerAdapter) { this.serializerAdapter = serializerAdapter; try { if (tableName == null) { throw new NullPointerException("'tableName' must not be null to create a TableClient."); } if (tableName.isEmpty()) { throw new IllegalArgumentException("'tableName' must not be empty to create a TableClient."); } final URI uri = URI.create(implementation.getUrl()); this.accountName = uri.getHost().split("\\.", 2)[0]; this.tableUrl = uri.resolve("/" + tableName).toString(); logger.verbose("Table Service URI: {}", uri); } catch (NullPointerException | IllegalArgumentException ex) { throw logger.logExceptionAsError(ex); } this.implementation = implementation; this.tableName = tableName; this.pipeline = implementation.getHttpPipeline(); } TableAsyncClient(String tableName, HttpPipeline pipeline, String serviceUrl, TablesServiceVersion serviceVersion, SerializerAdapter serializerAdapter) { this(tableName, new AzureTableImplBuilder() .url(serviceUrl) .serializerAdapter(serializerAdapter) .pipeline(pipeline) .version(serviceVersion.getVersion()) .buildClient(), serializerAdapter ); } /** * Gets the name of the table. * * @return The name of the table. */ public String getTableName() { return tableName; } /** * Gets the name of the account containing the table. * * @return The name of the account containing the table. */ public String getAccountName() { return accountName; } /** * Gets the absolute URL for this table. * * @return The absolute URL for this table. */ public String getTableUrl() { return tableUrl; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } /** * Gets the REST API version used by this client. * * @return The REST API version used by this client. */ public TablesServiceVersion getApiVersion() { return TablesServiceVersion.fromString(implementation.getVersion()); } /** * Creates a new {@link TableAsyncBatch} object. Batch objects allow you to enqueue multiple create, update, upsert, * and/or delete operations on entities that share the same partition key. When the batch is executed, all of the * operations will be performed as part of a single transaction. As a result, either all operations in the batch * will succeed, or if a failure occurs, all operations in the batch will be rolled back. Each operation in a batch * must operate on a distinct row key. Attempting to add multiple operations to a batch that share the same row key * will cause an exception to be thrown. * * @param partitionKey The partition key shared by all operations in the batch. * * @return An object representing the batch, to which operations can be added. * * @throws IllegalArgumentException If the provided partition key is {@code null} or empty. */ public TableAsyncBatch createBatch(String partitionKey) { if (isNullOrEmpty(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("'partitionKey' cannot be null or empty.")); } return new TableAsyncBatch(partitionKey, this); } AzureTableImpl getImplementation() { return implementation; } /** * Creates the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> create() { return createWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates the table within the Tables service. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createWithResponse() { return withContext(this::createWithResponse); } Mono<Response<Void>> createWithResponse(Context context) { context = context == null ? Context.NONE : context; final TableProperties properties = catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return An empty reactive result. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> createEntity(TableEntity entity) { return createEntityWithResponse(entity).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table. * * @param entity The entity to insert. * * @return A reactive result containing the HTTP response. * * @throws TableServiceErrorException If an entity with the same partition key and row key already exists within the * table. * @throws IllegalArgumentException If the provided entity is invalid. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> createEntityWithResponse(TableEntity entity) { return withContext(context -> createEntityWithResponse(entity, null, context)); } Mono<Response<Void>> createEntityWithResponse(TableEntity entity, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { return implementation.getTables().insertEntityWithResponseAsync(tableName, timeoutInt, null, ResponseFormat.RETURN_NO_CONTENT, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Inserts an entity into the table if it does not exist, or merges the entity with the existing entity otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the provided entity's properties will be merged into the existing entity. * * @param entity The entity to upsert. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity) { return upsertEntityWithResponse(entity, null).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> upsertEntity(TableEntity entity, UpdateMode updateMode) { return upsertEntityWithResponse(entity, updateMode).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Inserts an entity into the table if it does not exist, or updates the existing entity using the specified update * mode otherwise. * * If no entity exists within the table having the same partition key and row key as the provided entity, it will be * inserted. Otherwise, the existing entity will be updated according to the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to upsert. * @param updateMode The type of update to perform if the entity already exits. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode) { return withContext(context -> upsertEntityWithResponse(entity, updateMode, null, context)); } Mono<Response<Void>> upsertEntityWithResponse(TableEntity entity, UpdateMode updateMode, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, null, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates an existing entity by merging the provided entity with the existing entity. * * @param entity The entity to update. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity) { return updateEntity(entity, null); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode) { return updateEntity(entity, updateMode, false); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> updateEntity(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return updateEntityWithResponse(entity, updateMode, ifUnchanged).flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Updates an existing entity using the specified update mode. * * When the update mode is 'MERGE', the provided entity's properties will be merged into the existing entity. When * the update mode is 'REPLACE', the provided entity's properties will completely replace those in the existing * entity. * * @param entity The entity to update. * @param updateMode The type of update to perform. * @param ifUnchanged When true, the eTag of the provided entity must match the eTag of the entity in the Table * service. If the values do not match, the update will not occur and an exception will be thrown. * * @return A reactive result containing the HTTP response. * * @throws IllegalArgumentException If the provided entity is invalid. * @throws TableServiceErrorException If no entity with the same partition key and row key exists within the table, * or if {@code ifUnchanged} is {@code true} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged) { return withContext(context -> updateEntityWithResponse(entity, updateMode, ifUnchanged, null, context)); } Mono<Response<Void>> updateEntityWithResponse(TableEntity entity, UpdateMode updateMode, boolean ifUnchanged, Duration timeout, Context context) { context = context == null ? Context.NONE : context; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (entity == null) { return monoError(logger, new IllegalArgumentException("'entity' cannot be null.")); } String eTag = ifUnchanged ? entity.getETag() : "*"; EntityHelper.setPropertiesFromGetters(entity, logger); try { if (updateMode == UpdateMode.REPLACE) { return implementation.getTables().updateEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } else { return implementation.getTables().mergeEntityWithResponseAsync(tableName, entity.getPartitionKey(), entity.getRowKey(), timeoutInt, null, eTag, entity.getProperties(), null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes the table within the Tables service. * * @return An empty reactive result. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { return deleteWithResponse().flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the table within the Tables service. * * @return A reactive result containing the response. * * @throws TableServiceErrorException If no table with this name exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<Void>> deleteWithResponse(Context context) { context = context == null ? Context.NONE : context; try { return implementation.getTables().deleteWithResponseAsync(tableName, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response, null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey) { return deleteEntity(partitionKey, rowKey, null); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return An empty reactive result. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteEntity(String partitionKey, String rowKey, String eTag) { return deleteEntityWithResponse(partitionKey, rowKey, eTag).then(); } /** * Deletes an entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The row key of the entity. * @param eTag The value to compare with the eTag of the entity in the Tables service. If the values do not match, * the delete will not occur and an exception will be thrown. * * @return A reactive result containing the response. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table, or if {@code eTag} is not {@code null} and the existing entity's eTag does not match that of the provided * entity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag) { return withContext(context -> deleteEntityWithResponse(partitionKey, rowKey, eTag, null, context)); } Mono<Response<Void>> deleteEntityWithResponse(String partitionKey, String rowKey, String eTag, Duration timeout, Context context) { context = context == null ? Context.NONE : context; String matchParam = eTag == null ? "*" : eTag; Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().deleteEntityWithResponseAsync(tableName, partitionKey, rowKey, matchParam, timeoutInt, null, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists all entities within the table. * * @return A paged reactive result containing all entities within the table. * * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities() { return listEntities(new ListEntitiesOptions()); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TableEntity> listEntities(ListEntitiesOptions options) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, TableEntity.class)), token -> withContext(context -> listEntitiesNextPage(token, context, options, TableEntity.class))); } /** * Lists all entities within the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing all entities within the table. * * @throws IllegalArgumentException If an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(Class<T> resultType) { return listEntities(new ListEntitiesOptions(), resultType); } /** * Lists entities using the parameters in the provided options. * * If the `filter` parameter in the options is set, only entities matching the filter will be returned. If the * `select` parameter is set, only the properties included in the select parameter will be returned for each entity. * If the `top` parameter is set, the number of returned entities will be limited to that value. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param options The `filter`, `select`, and `top` OData query options to apply to this operation. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A paged reactive result containing matching entities within the table. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed, or if * an instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public <T extends TableEntity> PagedFlux<T> listEntities(ListEntitiesOptions options, Class<T> resultType) { return new PagedFlux<>( () -> withContext(context -> listEntitiesFirstPage(context, options, resultType)), token -> withContext(context -> listEntitiesNextPage(token, context, options, resultType))); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesFirstPage(Context context, ListEntitiesOptions options, Class<T> resultType) { return listEntities(null, null, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntitiesNextPage(String token, Context context, ListEntitiesOptions options, Class<T> resultType) { if (token == null) { return Mono.empty(); } String[] split = token.split(DELIMITER_CONTINUATION_TOKEN, 2); if (split.length != 2) { return monoError(logger, new RuntimeException( "Split done incorrectly, must have partition and row key: " + token)); } String nextPartitionKey = split[0]; String nextRowKey = split[1]; return listEntities(nextPartitionKey, nextRowKey, context, options, resultType); } private <T extends TableEntity> Mono<PagedResponse<T>> listEntities(String nextPartitionKey, String nextRowKey, Context context, ListEntitiesOptions options, Class<T> resultType) { context = context == null ? Context.NONE : context; QueryOptions queryOptions = new QueryOptions() .setFilter(options.getFilter()) .setTop(options.getTop()) .setSelect(options.getSelect()) .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); try { return implementation.getTables().queryEntitiesWithResponseAsync(tableName, null, null, nextPartitionKey, nextRowKey, queryOptions, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .flatMap(response -> { final TableEntityQueryResponse tablesQueryEntityResponse = response.getValue(); if (tablesQueryEntityResponse == null) { return Mono.empty(); } final List<Map<String, Object>> entityResponseValue = tablesQueryEntityResponse.getValue(); if (entityResponseValue == null) { return Mono.empty(); } final List<T> entities = entityResponseValue.stream() .map(ModelHelper::createEntity) .map(e -> EntityHelper.convertToSubclass(e, resultType, logger)) .collect(Collectors.toList()); return Mono.just(new EntityPaged<>(response, entities, response.getDeserializedHeaders().getXMsContinuationNextPartitionKey(), response.getDeserializedHeaders().getXMsContinuationNextRowKey())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private static class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey) { return getEntityWithResponse(partitionKey, rowKey, null).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TableEntity> getEntity(String partitionKey, String rowKey, String select) { return getEntityWithResponse(partitionKey, rowKey, select).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if an * instance of the provided {@code resultType} can't be created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, null, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<T> getEntity(String partitionKey, String rowKey, String select, Class<T> resultType) { return getEntityWithResponse(partitionKey, rowKey, select, resultType).flatMap(FluxUtil::toMono); } /** * Gets a single entity from the table. * * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, or if the * {@code select} OData query option is malformed. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TableEntity>> getEntityWithResponse(String partitionKey, String rowKey, String select) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, TableEntity.class, null, context)); } /** * Gets a single entity from the table. * * @param <T> The type of the result value, which must be a subclass of TableEntity. * @param partitionKey The partition key of the entity. * @param rowKey The partition key of the entity. * @param select An OData `select` expression to limit the set of properties included in the returned entity. * @param resultType The type of the result value, which must be a subclass of TableEntity. * * @return A reactive result containing the response and entity. * * @throws IllegalArgumentException If the provided partition key or row key are {@code null} or empty, if the * {@code select} OData query option is malformed, or if an instance of the provided {@code resultType} can't be * created. * @throws TableServiceErrorException If no entity with the provided partition key and row key exists within the * table. */ @ServiceMethod(returns = ReturnType.SINGLE) public <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType) { return withContext(context -> getEntityWithResponse(partitionKey, rowKey, select, resultType, null, context)); } <T extends TableEntity> Mono<Response<T>> getEntityWithResponse(String partitionKey, String rowKey, String select, Class<T> resultType, Duration timeout, Context context) { Integer timeoutInt = timeout == null ? null : (int) timeout.getSeconds(); QueryOptions queryOptions = new QueryOptions() .setFormat(OdataMetadataFormat.APPLICATION_JSON_ODATA_FULLMETADATA); if (select != null) { queryOptions.setSelect(select); } if (isNullOrEmpty(partitionKey) || isNullOrEmpty(rowKey)) { return monoError(logger, new IllegalArgumentException("'partitionKey' and 'rowKey' cannot be null.")); } try { return implementation.getTables().queryEntityWithPartitionAndRowKeyWithResponseAsync(tableName, partitionKey, rowKey, timeoutInt, null, queryOptions, context) .onErrorMap(TableUtils::mapThrowableToTableServiceErrorException) .handle((response, sink) -> { final Map<String, Object> matchingEntity = response.getValue(); if (matchingEntity == null || matchingEntity.isEmpty()) { logger.info("There was no matching entity. Table: {}, partition key: {}, row key: {}.", tableName, partitionKey, rowKey); sink.complete(); return; } final TableEntity entity = ModelHelper.createEntity(matchingEntity); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), EntityHelper.convertToSubclass(entity, resultType, logger))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Use the generic notation when using `List`.
private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final Section body = amqpMessage.getBody(); AmqpMessageBody amqpMessageBody = null; if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); amqpMessageBody = AmqpMessageBody.fromData(messageData.getArray()); } else if (body instanceof AmqpValue) { amqpMessageBody = AmqpMessageBody.fromValue(((AmqpValue)body).getValue()); } else if (body instanceof AmqpSequence) { List messageData = ((AmqpSequence) body).getValue(); amqpMessageBody = AmqpMessageBody.fromSequence(messageData); } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, body.getType())); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, "null")); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } final ServiceBusReceivedMessage brokeredMessage = new ServiceBusReceivedMessage(amqpMessageBody); AmqpAnnotatedMessage brokeredAmqpAnnotatedMessage = brokeredMessage.getRawAmqpMessage(); ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { final Map<String, Object> propertiesValue = applicationProperties.getValue(); brokeredAmqpAnnotatedMessage.getApplicationProperties().putAll(propertiesValue); } final AmqpMessageHeader brokeredHeader = brokeredAmqpAnnotatedMessage.getHeader(); brokeredHeader.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredHeader.setDeliveryCount(amqpMessage.getDeliveryCount()); brokeredHeader.setDurable(amqpMessage.getHeader().getDurable()); brokeredHeader.setFirstAcquirer(amqpMessage.getHeader().getFirstAcquirer()); brokeredHeader.setPriority(amqpMessage.getPriority()); final Footer footer = amqpMessage.getFooter(); if (footer != null && footer.getValue() != null) { @SuppressWarnings("unchecked") final Map<Symbol, Object> footerValue = footer.getValue(); setValues(footerValue, brokeredAmqpAnnotatedMessage.getFooter()); } final AmqpMessageProperties brokeredProperties = brokeredAmqpAnnotatedMessage.getProperties(); brokeredProperties.setReplyToGroupId(amqpMessage.getReplyToGroupId()); final String replyTo = amqpMessage.getReplyTo(); if (replyTo != null) { brokeredProperties.setReplyTo(new AmqpAddress(amqpMessage.getReplyTo())); } final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredProperties.setMessageId(new AmqpMessageId(messageId.toString())); } brokeredProperties.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredProperties.setCorrelationId(new AmqpMessageId(correlationId.toString())); } final Properties amqpProperties = amqpMessage.getProperties(); if (amqpProperties != null) { final String to = amqpProperties.getTo(); if (to != null) { brokeredProperties.setTo(new AmqpAddress(amqpProperties.getTo())); } if (amqpProperties.getAbsoluteExpiryTime() != null) { brokeredProperties.setAbsoluteExpiryTime(amqpProperties.getAbsoluteExpiryTime().toInstant() .atOffset(ZoneOffset.UTC)); } if (amqpProperties.getCreationTime() != null) { brokeredProperties.setCreationTime(amqpProperties.getCreationTime().toInstant() .atOffset(ZoneOffset.UTC)); } } brokeredProperties.setSubject(amqpMessage.getSubject()); brokeredProperties.setGroupId(amqpMessage.getGroupId()); brokeredProperties.setContentEncoding(amqpMessage.getContentEncoding()); brokeredProperties.setGroupSequence(amqpMessage.getGroupSequence()); brokeredProperties.setUserId(amqpMessage.getUserId()); final DeliveryAnnotations deliveryAnnotations = amqpMessage.getDeliveryAnnotations(); if (deliveryAnnotations != null) { setValues(deliveryAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getDeliveryAnnotations()); } final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { setValues(messageAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getMessageAnnotations()); } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; }
List messageData = ((AmqpSequence) body).getValue();
private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final Section body = amqpMessage.getBody(); AmqpMessageBody amqpMessageBody; if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); amqpMessageBody = AmqpMessageBody.fromData(messageData.getArray()); } else if (body instanceof AmqpValue) { amqpMessageBody = AmqpMessageBody.fromValue(((AmqpValue) body).getValue()); } else if (body instanceof AmqpSequence) { @SuppressWarnings("unchecked") List<Object> messageData = ((AmqpSequence) body).getValue(); amqpMessageBody = AmqpMessageBody.fromSequence(messageData); } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, body.getType())); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, "null")); amqpMessageBody = AmqpMessageBody.fromData(EMPTY_BYTE_ARRAY); } final ServiceBusReceivedMessage brokeredMessage = new ServiceBusReceivedMessage(amqpMessageBody); AmqpAnnotatedMessage brokeredAmqpAnnotatedMessage = brokeredMessage.getRawAmqpMessage(); ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { final Map<String, Object> propertiesValue = applicationProperties.getValue(); brokeredAmqpAnnotatedMessage.getApplicationProperties().putAll(propertiesValue); } final AmqpMessageHeader brokeredHeader = brokeredAmqpAnnotatedMessage.getHeader(); brokeredHeader.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredHeader.setDeliveryCount(amqpMessage.getDeliveryCount()); brokeredHeader.setDurable(amqpMessage.getHeader().getDurable()); brokeredHeader.setFirstAcquirer(amqpMessage.getHeader().getFirstAcquirer()); brokeredHeader.setPriority(amqpMessage.getPriority()); final Footer footer = amqpMessage.getFooter(); if (footer != null && footer.getValue() != null) { @SuppressWarnings("unchecked") final Map<Symbol, Object> footerValue = footer.getValue(); setValues(footerValue, brokeredAmqpAnnotatedMessage.getFooter()); } final AmqpMessageProperties brokeredProperties = brokeredAmqpAnnotatedMessage.getProperties(); brokeredProperties.setReplyToGroupId(amqpMessage.getReplyToGroupId()); final String replyTo = amqpMessage.getReplyTo(); if (replyTo != null) { brokeredProperties.setReplyTo(new AmqpAddress(amqpMessage.getReplyTo())); } final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredProperties.setMessageId(new AmqpMessageId(messageId.toString())); } brokeredProperties.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredProperties.setCorrelationId(new AmqpMessageId(correlationId.toString())); } final Properties amqpProperties = amqpMessage.getProperties(); if (amqpProperties != null) { final String to = amqpProperties.getTo(); if (to != null) { brokeredProperties.setTo(new AmqpAddress(amqpProperties.getTo())); } if (amqpProperties.getAbsoluteExpiryTime() != null) { brokeredProperties.setAbsoluteExpiryTime(amqpProperties.getAbsoluteExpiryTime().toInstant() .atOffset(ZoneOffset.UTC)); } if (amqpProperties.getCreationTime() != null) { brokeredProperties.setCreationTime(amqpProperties.getCreationTime().toInstant() .atOffset(ZoneOffset.UTC)); } } brokeredProperties.setSubject(amqpMessage.getSubject()); brokeredProperties.setGroupId(amqpMessage.getGroupId()); brokeredProperties.setContentEncoding(amqpMessage.getContentEncoding()); brokeredProperties.setGroupSequence(amqpMessage.getGroupSequence()); brokeredProperties.setUserId(amqpMessage.getUserId()); final DeliveryAnnotations deliveryAnnotations = amqpMessage.getDeliveryAnnotations(); if (deliveryAnnotations != null) { setValues(deliveryAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getDeliveryAnnotations()); } final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { setValues(messageAnnotations.getValue(), brokeredAmqpAnnotatedMessage.getMessageAnnotations()); } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private final ClientLogger logger = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; AmqpMessageBodyType brokeredBodyType = brokeredMessage.getRawAmqpMessage().getBody().getBodyType(); final Message amqpMessage = Proton.message(); byte[] body; if (brokeredBodyType == AmqpMessageBodyType.DATA || brokeredBodyType == null) { body = brokeredMessage.getBody().toBytes(); amqpMessage.setBody(new Data(new Binary(body))); } else if (brokeredBodyType == AmqpMessageBodyType.SEQUENCE) { List<Object> sequenceList = brokeredMessage.getRawAmqpMessage().getBody().getSequence(); amqpMessage.setBody(new AmqpSequence(sequenceList)); } else if (brokeredBodyType == AmqpMessageBodyType.VALUE) { amqpMessage.setBody(new AmqpValue(brokeredMessage.getRawAmqpMessage().getBody().getValue())); } if (brokeredMessage.getApplicationProperties() != null) { amqpMessage.setApplicationProperties(new ApplicationProperties(brokeredMessage.getApplicationProperties())); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getSubject()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final AmqpMessageProperties brokeredProperties = brokeredMessage.getRawAmqpMessage().getProperties(); amqpMessage.setContentEncoding(brokeredProperties.getContentEncoding()); if (brokeredProperties.getGroupSequence() != null) { amqpMessage.setGroupSequence(brokeredProperties.getGroupSequence()); } amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.getProperties().setUserId(new Binary(brokeredProperties.getUserId())); if (brokeredProperties.getAbsoluteExpiryTime() != null) { amqpMessage.getProperties().setAbsoluteExpiryTime(Date.from(brokeredProperties.getAbsoluteExpiryTime() .toInstant())); } if (brokeredProperties.getCreationTime() != null) { amqpMessage.getProperties().setCreationTime(Date.from(brokeredProperties.getCreationTime().toInstant())); } amqpMessage.setFooter(new Footer(brokeredMessage.getRawAmqpMessage().getFooter())); AmqpMessageHeader header = brokeredMessage.getRawAmqpMessage().getHeader(); if (header.getDeliveryCount() != null) { amqpMessage.setDeliveryCount(header.getDeliveryCount()); } if (header.getPriority() != null) { amqpMessage.setPriority(header.getPriority()); } if (header.isDurable() != null) { amqpMessage.setDurable(header.isDurable()); } if (header.isFirstAcquirer() != null) { amqpMessage.setFirstAcquirer(header.isFirstAcquirer()); } if (header.getTimeToLive() != null) { amqpMessage.setTtl(header.getTimeToLive().toMillis()); } final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()), Date.from(brokeredMessage.getScheduledEnqueueTime().toInstant())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_ANNOTATION_NAME.getValue()), brokeredMessage.getPartitionKey()); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); final Map<Symbol, Object> deliveryAnnotationsMap = new HashMap<>(); final Map<String, Object> deliveryAnnotations = brokeredMessage.getRawAmqpMessage() .getDeliveryAnnotations(); for (Map.Entry<String, Object> deliveryEntry : deliveryAnnotations.entrySet()) { deliveryAnnotationsMap.put(Symbol.valueOf(deliveryEntry.getKey()), deliveryEntry.getValue()); } amqpMessage.setDeliveryAnnotations(new DeliveryAnnotations(deliveryAnnotationsMap)); return amqpMessage; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == Long.class) { return (List<T>) deserializeListOfLong(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } private List<Long> deserializeListOfLong(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.SEQUENCE_NUMBERS); if (expirationListObj instanceof long[]) { return Arrays.stream((long[]) expirationListObj) .boxed() .collect(Collectors.toList()); } } } return Collections.emptyList(); } private List<OffsetDateTime> deserializeListOfOffsetDateTime(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.EXPIRATIONS); if (expirationListObj instanceof Date[]) { return Arrays.stream((Date[]) expirationListObj) .map(date -> date.toInstant().atOffset(ZoneOffset.UTC)) .collect(Collectors.toList()); } } } return Collections.emptyList(); } @SuppressWarnings("rawtypes") private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(amqpMessage); if (statusCode != AmqpResponseCode.OK) { logger.warning("AMQP response did not contain OK status code. Actual: {}", statusCode); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { logger.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { logger.warning("AMQP response body is not correct instance. Expected: {}. Actual: {}", Map.class, responseBodyMap.getClass()); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(ManagementConstants.MESSAGES); if (messages == null) { logger.warning("Response body did not contain key: {}", ManagementConstants.MESSAGES); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { logger.warning("Response body contents is not the correct type. Expected: {}. Actual: {}", Iterable.class, messages.getClass()); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { logger.warning("Message inside iterable of message is not correct type. Expected: {}. Actual: {}", Map.class, message.getClass()); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(ManagementConstants.MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); if (((Map) message).containsKey(ManagementConstants.LOCK_TOKEN_KEY)) { receivedMessage.setLockToken((UUID) ((Map) message).get(ManagementConstants.LOCK_TOKEN_KEY)); } messageList.add(receivedMessage); } return messageList; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } private void setValues(Map<Symbol, Object> sourceMap, Map<String, Object> targetMap) { if (sourceMap != null) { for (Map.Entry<Symbol, Object> entry : sourceMap.entrySet()) { targetMap.put(entry.getKey().toString(), entry.getValue()); } } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private final ClientLogger logger = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; AmqpMessageBodyType brokeredBodyType = brokeredMessage.getRawAmqpMessage().getBody().getBodyType(); final Message amqpMessage = Proton.message(); byte[] body; if (brokeredBodyType == AmqpMessageBodyType.DATA || brokeredBodyType == null) { body = brokeredMessage.getBody().toBytes(); amqpMessage.setBody(new Data(new Binary(body))); } else if (brokeredBodyType == AmqpMessageBodyType.SEQUENCE) { List<Object> sequenceList = brokeredMessage.getRawAmqpMessage().getBody().getSequence(); amqpMessage.setBody(new AmqpSequence(sequenceList)); } else if (brokeredBodyType == AmqpMessageBodyType.VALUE) { amqpMessage.setBody(new AmqpValue(brokeredMessage.getRawAmqpMessage().getBody().getValue())); } if (brokeredMessage.getApplicationProperties() != null) { amqpMessage.setApplicationProperties(new ApplicationProperties(brokeredMessage.getApplicationProperties())); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getSubject()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final AmqpMessageProperties brokeredProperties = brokeredMessage.getRawAmqpMessage().getProperties(); amqpMessage.setContentEncoding(brokeredProperties.getContentEncoding()); if (brokeredProperties.getGroupSequence() != null) { amqpMessage.setGroupSequence(brokeredProperties.getGroupSequence()); } amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.getProperties().setUserId(new Binary(brokeredProperties.getUserId())); if (brokeredProperties.getAbsoluteExpiryTime() != null) { amqpMessage.getProperties().setAbsoluteExpiryTime(Date.from(brokeredProperties.getAbsoluteExpiryTime() .toInstant())); } if (brokeredProperties.getCreationTime() != null) { amqpMessage.getProperties().setCreationTime(Date.from(brokeredProperties.getCreationTime().toInstant())); } amqpMessage.setFooter(new Footer(brokeredMessage.getRawAmqpMessage().getFooter())); AmqpMessageHeader header = brokeredMessage.getRawAmqpMessage().getHeader(); if (header.getDeliveryCount() != null) { amqpMessage.setDeliveryCount(header.getDeliveryCount()); } if (header.getPriority() != null) { amqpMessage.setPriority(header.getPriority()); } if (header.isDurable() != null) { amqpMessage.setDurable(header.isDurable()); } if (header.isFirstAcquirer() != null) { amqpMessage.setFirstAcquirer(header.isFirstAcquirer()); } if (header.getTimeToLive() != null) { amqpMessage.setTtl(header.getTimeToLive().toMillis()); } final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()), Date.from(brokeredMessage.getScheduledEnqueueTime().toInstant())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_ANNOTATION_NAME.getValue()), brokeredMessage.getPartitionKey()); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); final Map<Symbol, Object> deliveryAnnotationsMap = new HashMap<>(); final Map<String, Object> deliveryAnnotations = brokeredMessage.getRawAmqpMessage() .getDeliveryAnnotations(); for (Map.Entry<String, Object> deliveryEntry : deliveryAnnotations.entrySet()) { deliveryAnnotationsMap.put(Symbol.valueOf(deliveryEntry.getKey()), deliveryEntry.getValue()); } amqpMessage.setDeliveryAnnotations(new DeliveryAnnotations(deliveryAnnotationsMap)); return amqpMessage; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == OffsetDateTime.class) { return (List<T>) deserializeListOfOffsetDateTime(message); } else if (clazz == Long.class) { return (List<T>) deserializeListOfLong(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Messages.CLASS_NOT_A_SUPPORTED_TYPE, clazz))); } } private List<Long> deserializeListOfLong(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.SEQUENCE_NUMBERS); if (expirationListObj instanceof long[]) { return Arrays.stream((long[]) expirationListObj) .boxed() .collect(Collectors.toList()); } } } return Collections.emptyList(); } private List<OffsetDateTime> deserializeListOfOffsetDateTime(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(ManagementConstants.EXPIRATIONS); if (expirationListObj instanceof Date[]) { return Arrays.stream((Date[]) expirationListObj) .map(date -> date.toInstant().atOffset(ZoneOffset.UTC)) .collect(Collectors.toList()); } } } return Collections.emptyList(); } @SuppressWarnings("rawtypes") private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(amqpMessage); if (statusCode != AmqpResponseCode.OK) { logger.warning("AMQP response did not contain OK status code. Actual: {}", statusCode); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { logger.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { logger.warning("AMQP response body is not correct instance. Expected: {}. Actual: {}", Map.class, responseBodyMap.getClass()); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(ManagementConstants.MESSAGES); if (messages == null) { logger.warning("Response body did not contain key: {}", ManagementConstants.MESSAGES); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { logger.warning("Response body contents is not the correct type. Expected: {}. Actual: {}", Iterable.class, messages.getClass()); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { logger.warning("Message inside iterable of message is not correct type. Expected: {}. Actual: {}", Map.class, message.getClass()); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(ManagementConstants.MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); if (((Map) message).containsKey(ManagementConstants.LOCK_TOKEN_KEY)) { receivedMessage.setLockToken((UUID) ((Map) message).get(ManagementConstants.LOCK_TOKEN_KEY)); } messageList.add(receivedMessage); } return messageList; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } private void setValues(Map<Symbol, Object> sourceMap, Map<String, Object> targetMap) { if (sourceMap != null) { for (Map.Entry<Symbol, Object> entry : sourceMap.entrySet()) { targetMap.put(entry.getKey().toString(), entry.getValue()); } } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
remove this line?
public void checkBodyType() { AmqpAnnotatedMessage amqpAnnotatedMessage = null; Object amqpValue; AmqpMessageBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: byte[] payload = amqpAnnotatedMessage.getBody().getFirstData(); System.out.println(new String(payload)); break; case SEQUENCE: List<Object> sequenceData = amqpAnnotatedMessage.getBody().getSequence(); sequenceData.forEach(System.out::println); break; case VALUE: amqpValue = amqpAnnotatedMessage.getBody().getValue(); System.out.println(amqpValue); break; default: throw new RuntimeException("Body type is not valid."); } }
System.out.println(amqpValue);
public void checkBodyType() { AmqpAnnotatedMessage amqpAnnotatedMessage = null; Object amqpValue; AmqpMessageBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: byte[] payload = amqpAnnotatedMessage.getBody().getFirstData(); System.out.println(new String(payload)); break; case SEQUENCE: List<Object> sequenceData = amqpAnnotatedMessage.getBody().getSequence(); sequenceData.forEach(System.out::println); break; case VALUE: amqpValue = amqpAnnotatedMessage.getBody().getValue(); System.out.println(amqpValue); break; default: throw new RuntimeException(String.format(Locale.US, "Body type [%s] is not valid.", bodyType)); } }
class AmqpAnnotatedMessageJavaDocCodeSamples { /** * Get message body from {@link AmqpAnnotatedMessage}. */ public void address() { AmqpAddress amqpAddress = new AmqpAddress("my-address"); String address = amqpAddress.toString(); System.out.println("Address " + address); } /** * Get message body from {@link AmqpMessageId}. */ public void messageId() { AmqpMessageId messageId = new AmqpMessageId("my-message-id"); String id = messageId.toString(); System.out.println("Message Id " + id); } }
class AmqpAnnotatedMessageJavaDocCodeSamples { /** * Get message body from {@link AmqpAnnotatedMessage}. */ public void address() { AmqpAddress amqpAddress = new AmqpAddress("my-address"); String address = amqpAddress.toString(); System.out.println("Address " + address); } /** * Get message body from {@link AmqpMessageId}. */ public void messageId() { AmqpMessageId messageId = new AmqpMessageId("my-message-id"); String id = messageId.toString(); System.out.println("Message Id " + id); } }
it would better to provide "type" info in the exception message , like which type is not valid
public void checkBodyType() { AmqpAnnotatedMessage amqpAnnotatedMessage = null; Object amqpValue; AmqpMessageBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: byte[] payload = amqpAnnotatedMessage.getBody().getFirstData(); System.out.println(new String(payload)); break; case SEQUENCE: List<Object> sequenceData = amqpAnnotatedMessage.getBody().getSequence(); sequenceData.forEach(System.out::println); break; case VALUE: amqpValue = amqpAnnotatedMessage.getBody().getValue(); System.out.println(amqpValue); break; default: throw new RuntimeException("Body type is not valid."); } }
throw new RuntimeException("Body type is not valid.");
public void checkBodyType() { AmqpAnnotatedMessage amqpAnnotatedMessage = null; Object amqpValue; AmqpMessageBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: byte[] payload = amqpAnnotatedMessage.getBody().getFirstData(); System.out.println(new String(payload)); break; case SEQUENCE: List<Object> sequenceData = amqpAnnotatedMessage.getBody().getSequence(); sequenceData.forEach(System.out::println); break; case VALUE: amqpValue = amqpAnnotatedMessage.getBody().getValue(); System.out.println(amqpValue); break; default: throw new RuntimeException(String.format(Locale.US, "Body type [%s] is not valid.", bodyType)); } }
class AmqpAnnotatedMessageJavaDocCodeSamples { /** * Get message body from {@link AmqpAnnotatedMessage}. */ public void address() { AmqpAddress amqpAddress = new AmqpAddress("my-address"); String address = amqpAddress.toString(); System.out.println("Address " + address); } /** * Get message body from {@link AmqpMessageId}. */ public void messageId() { AmqpMessageId messageId = new AmqpMessageId("my-message-id"); String id = messageId.toString(); System.out.println("Message Id " + id); } }
class AmqpAnnotatedMessageJavaDocCodeSamples { /** * Get message body from {@link AmqpAnnotatedMessage}. */ public void address() { AmqpAddress amqpAddress = new AmqpAddress("my-address"); String address = amqpAddress.toString(); System.out.println("Address " + address); } /** * Get message body from {@link AmqpMessageId}. */ public void messageId() { AmqpMessageId messageId = new AmqpMessageId("my-message-id"); String id = messageId.toString(); System.out.println("Message Id " + id); } }
It is fine because we are outputting the value in same , so user can see it.
public void checkBodyType() { AmqpAnnotatedMessage amqpAnnotatedMessage = null; Object amqpValue; AmqpMessageBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: byte[] payload = amqpAnnotatedMessage.getBody().getFirstData(); System.out.println(new String(payload)); break; case SEQUENCE: List<Object> sequenceData = amqpAnnotatedMessage.getBody().getSequence(); sequenceData.forEach(System.out::println); break; case VALUE: amqpValue = amqpAnnotatedMessage.getBody().getValue(); System.out.println(amqpValue); break; default: throw new RuntimeException("Body type is not valid."); } }
System.out.println(amqpValue);
public void checkBodyType() { AmqpAnnotatedMessage amqpAnnotatedMessage = null; Object amqpValue; AmqpMessageBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: byte[] payload = amqpAnnotatedMessage.getBody().getFirstData(); System.out.println(new String(payload)); break; case SEQUENCE: List<Object> sequenceData = amqpAnnotatedMessage.getBody().getSequence(); sequenceData.forEach(System.out::println); break; case VALUE: amqpValue = amqpAnnotatedMessage.getBody().getValue(); System.out.println(amqpValue); break; default: throw new RuntimeException(String.format(Locale.US, "Body type [%s] is not valid.", bodyType)); } }
class AmqpAnnotatedMessageJavaDocCodeSamples { /** * Get message body from {@link AmqpAnnotatedMessage}. */ public void address() { AmqpAddress amqpAddress = new AmqpAddress("my-address"); String address = amqpAddress.toString(); System.out.println("Address " + address); } /** * Get message body from {@link AmqpMessageId}. */ public void messageId() { AmqpMessageId messageId = new AmqpMessageId("my-message-id"); String id = messageId.toString(); System.out.println("Message Id " + id); } }
class AmqpAnnotatedMessageJavaDocCodeSamples { /** * Get message body from {@link AmqpAnnotatedMessage}. */ public void address() { AmqpAddress amqpAddress = new AmqpAddress("my-address"); String address = amqpAddress.toString(); System.out.println("Address " + address); } /** * Get message body from {@link AmqpMessageId}. */ public void messageId() { AmqpMessageId messageId = new AmqpMessageId("my-message-id"); String id = messageId.toString(); System.out.println("Message Id " + id); } }
good catch.
public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return BinaryData.fromBytes(amqpAnnotatedMessage.getBody().getFirstData()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new IllegalStateException("Message body type is not DATA, instead " + "it is: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
"it is: " + type.toString()));
public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return BinaryData.fromBytes(amqpAnnotatedMessage.getBody().getFirstData()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new IllegalStateException("Message body type is not DATA, instead " + "it is: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
class ServiceBusMessage { private static final int MAX_MESSAGE_ID_LENGTH = 128; private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final int MAX_SESSION_ID_LENGTH = 128; private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} with a {@link StandardCharsets * * @param body The content of the Service Bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into {@link * BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(body.toBytes())); } /** * This constructor provides an easy way to create {@link ServiceBusMessage} with message body as AMQP Data types * {@code SEQUENCE} and {@code VALUE}. It support sending and receiving of only one AMQP Sequence at present. * If you are sending message with single byte array or String data, you can also use other constructor. * * @param amqpMessageBody amqp message body. * * @throws NullPointerException if {@code amqpMessageBody} is {@code null}. */ public ServiceBusMessage(AmqpMessageBody amqpMessageBody) { Objects.requireNonNull(amqpMessageBody, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. * @throws UnsupportedOperationException if {@link AmqpMessageBodyType} is {@link AmqpMessageBodyType * or {@link AmqpMessageBodyType * @throws IllegalStateException for invalid {@link AmqpMessageBodyType}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); final AmqpMessageBodyType bodyType = receivedMessage.getRawAmqpMessage().getBody().getBodyType(); AmqpMessageBody amqpMessageBody; switch (bodyType) { case DATA: amqpMessageBody = AmqpMessageBody.fromData(receivedMessage.getRawAmqpMessage().getBody() .getFirstData()); break; case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException( "This constructor only supports the AMQP Data body type at present. Track this issue, " + "https: + "future.")); default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); final AmqpMessageProperties receivedProperties = receivedMessage.getRawAmqpMessage().getProperties(); final AmqpMessageProperties newProperties = amqpAnnotatedMessage.getProperties(); newProperties.setMessageId(receivedProperties.getMessageId()); newProperties.setUserId(receivedProperties.getUserId()); newProperties.setTo(receivedProperties.getTo()); newProperties.setSubject(receivedProperties.getSubject()); newProperties.setReplyTo(receivedProperties.getReplyTo()); newProperties.setCorrelationId(receivedProperties.getCorrelationId()); newProperties.setContentType(receivedProperties.getContentType()); newProperties.setContentEncoding(receivedProperties.getContentEncoding()); newProperties.setAbsoluteExpiryTime(receivedProperties.getAbsoluteExpiryTime()); newProperties.setCreationTime(receivedProperties.getCreationTime()); newProperties.setGroupId(receivedProperties.getGroupId()); newProperties.setGroupSequence(receivedProperties.getGroupSequence()); newProperties.setReplyToGroupId(receivedProperties.getReplyToGroupId()); final AmqpMessageHeader receivedHeader = receivedMessage.getRawAmqpMessage().getHeader(); final AmqpMessageHeader newHeader = this.amqpAnnotatedMessage.getHeader(); newHeader.setPriority(receivedHeader.getPriority()); newHeader.setTimeToLive(receivedHeader.getTimeToLive()); newHeader.setDurable(receivedHeader.isDurable()); newHeader.setFirstAcquirer(receivedHeader.isFirstAcquirer()); final Map<String, Object> receivedAnnotations = receivedMessage.getRawAmqpMessage() .getMessageAnnotations(); final Map<String, Object> newAnnotations = this.amqpAnnotatedMessage.getMessageAnnotations(); for (Map.Entry<String, Object> entry : receivedAnnotations.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == LOCKED_UNTIL_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_TIME_UTC_ANNOTATION_NAME) { continue; } newAnnotations.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedDelivery = receivedMessage.getRawAmqpMessage().getDeliveryAnnotations(); final Map<String, Object> newDelivery = this.amqpAnnotatedMessage.getDeliveryAnnotations(); for (Map.Entry<String, Object> entry : receivedDelivery.entrySet()) { newDelivery.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedFooter = receivedMessage.getRawAmqpMessage().getFooter(); final Map<String, Object> newFooter = this.amqpAnnotatedMessage.getFooter(); for (Map.Entry<String, Object> entry : receivedFooter.entrySet()) { newFooter.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedApplicationProperties = receivedMessage.getRawAmqpMessage() .getApplicationProperties(); final Map<String, Object> newApplicationProperties = this.amqpAnnotatedMessage.getApplicationProperties(); for (Map.Entry<String, Object> entry : receivedApplicationProperties.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_REASON_ANNOTATION_NAME) { continue; } newApplicationProperties.put(entry.getKey(), entry.getValue()); } this.context = Context.NONE; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code * getApplicationProperties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides convenience APIs to serialize/deserialize the object.</p> * * <p>If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use * of {@link * consumers who wish to deserialize the binary data.</p> * * @throws IllegalStateException if called for the messages which are not of binary data type. * @return Binary data representing the payload. */ /** * Gets the content type of the message. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * @return The content type of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * * @param contentType RFC2045 Content-Type descriptor of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return The correlation id of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { String correlationId = null; AmqpMessageId amqpCorrelationId = amqpAnnotatedMessage.getProperties().getCorrelationId(); if (amqpCorrelationId != null) { correlationId = amqpCorrelationId.toString(); } return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { AmqpMessageId id = null; if (correlationId != null) { id = new AmqpMessageId(correlationId); } amqpAnnotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the subject for the message. * * <p> * This property enables the application to indicate the purpose of the message to the receiver in a standardized * fashion, similar to an email subject line. The mapped AMQP property is "subject". * </p> * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The application specific subject. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If * enabled, the * <a href="https: * feature identifies and removes second and further submissions of messages with the same {@code messageId}. * </p> * * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { String messageId = null; AmqpMessageId amqpMessageId = amqpAnnotatedMessage.getProperties().getMessageId(); if (amqpMessageId != null) { messageId = amqpMessageId.toString(); } return messageId; } /** * Sets the message id. * * @param messageId The message id to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public ServiceBusMessage setMessageId(String messageId) { checkIdLength("messageId", messageId, MAX_MESSAGE_ID_LENGTH); AmqpMessageId id = null; if (messageId != null) { id = new AmqpMessageId(messageId); } amqpAnnotatedMessage.getProperties().setMessageId(id); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * </p> * * @return The partition key of this message. * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey The partition key of this message. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code partitionKey} is too long or if the {@code partitionKey} does not * match the {@code sessionId}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { checkIdLength("partitionKey", partitionKey, MAX_PARTITION_KEY_LENGTH); checkPartitionKey(partitionKey); amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return The raw AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return amqpAnnotatedMessage; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { String replyTo = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getReplyTo(); if (amqpAddress != null) { replyTo = amqpAddress.toString(); } return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { AmqpAddress replyToAddress = null; if (replyTo != null) { replyToAddress = new AmqpAddress(replyTo); } amqpAnnotatedMessage.getProperties().setReplyTo(replyToAddress); return this; } /** * Gets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @return "To" property value of this message */ public String getTo() { String to = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getTo(); if (amqpAddress != null) { to = amqpAddress.toString(); } return to; } /** * Sets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @param to To property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { AmqpAddress toAddress = null; if (to != null) { toAddress = new AmqpAddress(to); } amqpAnnotatedMessage.getProperties().setTo(toAddress); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the {@link * be set for the reply when sent to the reply entity. * * @return The {@code getReplyToGroupId} property value of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId The ReplyToGroupId property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the session identifier for a session-aware entity. * * <p> * For session-aware entities, this application-defined value specifies the session affiliation of the message. * Messages with the same session identifier are subject to summary locking and enable exact in-order processing and * demultiplexing. For session-unaware entities, this value is ignored. See <a * href="https: * </p> * * @return The session id of the {@link ServiceBusMessage}. * @see <a href="https: */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session identifier for a session-aware entity. * * @param sessionId The session identifier to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code sessionId} is too long or if the {@code sessionId} does not match * the {@code partitionKey}. */ public ServiceBusMessage setSessionId(String sessionId) { checkIdLength("sessionId", sessionId, MAX_SESSION_ID_LENGTH); checkSessionId(sessionId); amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /** * Checks the length of ID fields. * * Some fields within the message will cause a failure in the service without enough context information. */ private void checkIdLength(String fieldName, String value, int maxLength) { if (value != null && value.length() > maxLength) { final String message = String.format("%s cannot be longer than %d characters.", fieldName, maxLength); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkSessionId(String proposedSessionId) { if (proposedSessionId == null) { return; } if (this.getPartitionKey() != null && this.getPartitionKey().compareTo(proposedSessionId) != 0) { final String message = String.format( "sessionId:%s cannot be set to a different value than partitionKey:%s.", proposedSessionId, this.getPartitionKey()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkPartitionKey(String proposedPartitionKey) { if (proposedPartitionKey == null) { return; } if (this.getSessionId() != null && this.getSessionId().compareTo(proposedPartitionKey) != 0) { final String message = String.format( "partitionKey:%s cannot be set to a different value than sessionId:%s.", proposedPartitionKey, this.getSessionId()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } }
class ServiceBusMessage { private static final int MAX_MESSAGE_ID_LENGTH = 128; private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final int MAX_SESSION_ID_LENGTH = 128; private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} with a {@link StandardCharsets * * @param body The content of the Service Bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into {@link * BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(body.toBytes())); } /** * This constructor provides an easy way to create {@link ServiceBusMessage} with message body as AMQP Data types * {@code SEQUENCE} and {@code VALUE}. * In case of {@code SEQUENCE}, tt support sending and receiving of only one AMQP Sequence at present. * If you are sending message with single byte array or String data, you can also use other constructor. * * @param amqpMessageBody amqp message body. * * @throws NullPointerException if {@code amqpMessageBody} is {@code null}. */ public ServiceBusMessage(AmqpMessageBody amqpMessageBody) { Objects.requireNonNull(amqpMessageBody, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. * @throws IllegalStateException for invalid {@link AmqpMessageBodyType}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); final AmqpMessageBodyType bodyType = receivedMessage.getRawAmqpMessage().getBody().getBodyType(); AmqpMessageBody amqpMessageBody; switch (bodyType) { case DATA: amqpMessageBody = AmqpMessageBody.fromData(receivedMessage.getRawAmqpMessage().getBody() .getFirstData()); break; case SEQUENCE: amqpMessageBody = AmqpMessageBody.fromSequence(receivedMessage.getRawAmqpMessage().getBody() .getSequence()); break; case VALUE: amqpMessageBody = AmqpMessageBody.fromValue(receivedMessage.getRawAmqpMessage().getBody() .getValue()); break; default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); final AmqpMessageProperties receivedProperties = receivedMessage.getRawAmqpMessage().getProperties(); final AmqpMessageProperties newProperties = amqpAnnotatedMessage.getProperties(); newProperties.setMessageId(receivedProperties.getMessageId()); newProperties.setUserId(receivedProperties.getUserId()); newProperties.setTo(receivedProperties.getTo()); newProperties.setSubject(receivedProperties.getSubject()); newProperties.setReplyTo(receivedProperties.getReplyTo()); newProperties.setCorrelationId(receivedProperties.getCorrelationId()); newProperties.setContentType(receivedProperties.getContentType()); newProperties.setContentEncoding(receivedProperties.getContentEncoding()); newProperties.setAbsoluteExpiryTime(receivedProperties.getAbsoluteExpiryTime()); newProperties.setCreationTime(receivedProperties.getCreationTime()); newProperties.setGroupId(receivedProperties.getGroupId()); newProperties.setGroupSequence(receivedProperties.getGroupSequence()); newProperties.setReplyToGroupId(receivedProperties.getReplyToGroupId()); final AmqpMessageHeader receivedHeader = receivedMessage.getRawAmqpMessage().getHeader(); final AmqpMessageHeader newHeader = this.amqpAnnotatedMessage.getHeader(); newHeader.setPriority(receivedHeader.getPriority()); newHeader.setTimeToLive(receivedHeader.getTimeToLive()); newHeader.setDurable(receivedHeader.isDurable()); newHeader.setFirstAcquirer(receivedHeader.isFirstAcquirer()); final Map<String, Object> receivedAnnotations = receivedMessage.getRawAmqpMessage() .getMessageAnnotations(); final Map<String, Object> newAnnotations = this.amqpAnnotatedMessage.getMessageAnnotations(); for (Map.Entry<String, Object> entry : receivedAnnotations.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == LOCKED_UNTIL_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_TIME_UTC_ANNOTATION_NAME) { continue; } newAnnotations.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedDelivery = receivedMessage.getRawAmqpMessage().getDeliveryAnnotations(); final Map<String, Object> newDelivery = this.amqpAnnotatedMessage.getDeliveryAnnotations(); for (Map.Entry<String, Object> entry : receivedDelivery.entrySet()) { newDelivery.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedFooter = receivedMessage.getRawAmqpMessage().getFooter(); final Map<String, Object> newFooter = this.amqpAnnotatedMessage.getFooter(); for (Map.Entry<String, Object> entry : receivedFooter.entrySet()) { newFooter.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedApplicationProperties = receivedMessage.getRawAmqpMessage() .getApplicationProperties(); final Map<String, Object> newApplicationProperties = this.amqpAnnotatedMessage.getApplicationProperties(); for (Map.Entry<String, Object> entry : receivedApplicationProperties.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_REASON_ANNOTATION_NAME) { continue; } newApplicationProperties.put(entry.getKey(), entry.getValue()); } this.context = Context.NONE; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code * getApplicationProperties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides convenience APIs to serialize/deserialize the object.</p> * * <p>If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use * of {@link * consumers who wish to deserialize the binary data.</p> * * @throws IllegalStateException if called for the messages which are not of binary data type. * @return Binary data representing the payload. */ /** * Gets the content type of the message. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * @return The content type of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * * @param contentType RFC2045 Content-Type descriptor of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return The correlation id of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { String correlationId = null; AmqpMessageId amqpCorrelationId = amqpAnnotatedMessage.getProperties().getCorrelationId(); if (amqpCorrelationId != null) { correlationId = amqpCorrelationId.toString(); } return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { AmqpMessageId id = null; if (correlationId != null) { id = new AmqpMessageId(correlationId); } amqpAnnotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the subject for the message. * * <p> * This property enables the application to indicate the purpose of the message to the receiver in a standardized * fashion, similar to an email subject line. The mapped AMQP property is "subject". * </p> * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The application specific subject. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If * enabled, the * <a href="https: * feature identifies and removes second and further submissions of messages with the same {@code messageId}. * </p> * * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { String messageId = null; AmqpMessageId amqpMessageId = amqpAnnotatedMessage.getProperties().getMessageId(); if (amqpMessageId != null) { messageId = amqpMessageId.toString(); } return messageId; } /** * Sets the message id. * * @param messageId The message id to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public ServiceBusMessage setMessageId(String messageId) { checkIdLength("messageId", messageId, MAX_MESSAGE_ID_LENGTH); AmqpMessageId id = null; if (messageId != null) { id = new AmqpMessageId(messageId); } amqpAnnotatedMessage.getProperties().setMessageId(id); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * </p> * * @return The partition key of this message. * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey The partition key of this message. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code partitionKey} is too long or if the {@code partitionKey} does not * match the {@code sessionId}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { checkIdLength("partitionKey", partitionKey, MAX_PARTITION_KEY_LENGTH); checkPartitionKey(partitionKey); amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return The raw AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return amqpAnnotatedMessage; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { String replyTo = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getReplyTo(); if (amqpAddress != null) { replyTo = amqpAddress.toString(); } return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { AmqpAddress replyToAddress = null; if (replyTo != null) { replyToAddress = new AmqpAddress(replyTo); } amqpAnnotatedMessage.getProperties().setReplyTo(replyToAddress); return this; } /** * Gets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @return "To" property value of this message */ public String getTo() { String to = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getTo(); if (amqpAddress != null) { to = amqpAddress.toString(); } return to; } /** * Sets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @param to To property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { AmqpAddress toAddress = null; if (to != null) { toAddress = new AmqpAddress(to); } amqpAnnotatedMessage.getProperties().setTo(toAddress); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the {@link * be set for the reply when sent to the reply entity. * * @return The {@code getReplyToGroupId} property value of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId The ReplyToGroupId property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the session identifier for a session-aware entity. * * <p> * For session-aware entities, this application-defined value specifies the session affiliation of the message. * Messages with the same session identifier are subject to summary locking and enable exact in-order processing and * demultiplexing. For session-unaware entities, this value is ignored. See <a * href="https: * </p> * * @return The session id of the {@link ServiceBusMessage}. * @see <a href="https: */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session identifier for a session-aware entity. * * @param sessionId The session identifier to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code sessionId} is too long or if the {@code sessionId} does not match * the {@code partitionKey}. */ public ServiceBusMessage setSessionId(String sessionId) { checkIdLength("sessionId", sessionId, MAX_SESSION_ID_LENGTH); checkSessionId(sessionId); amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /** * Checks the length of ID fields. * * Some fields within the message will cause a failure in the service without enough context information. */ private void checkIdLength(String fieldName, String value, int maxLength) { if (value != null && value.length() > maxLength) { final String message = String.format("%s cannot be longer than %d characters.", fieldName, maxLength); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkSessionId(String proposedSessionId) { if (proposedSessionId == null) { return; } if (this.getPartitionKey() != null && this.getPartitionKey().compareTo(proposedSessionId) != 0) { final String message = String.format( "sessionId:%s cannot be set to a different value than partitionKey:%s.", proposedSessionId, this.getPartitionKey()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkPartitionKey(String proposedPartitionKey) { if (proposedPartitionKey == null) { return; } if (this.getSessionId() != null && this.getSessionId().compareTo(proposedPartitionKey) != 0) { final String message = String.format( "partitionKey:%s cannot be set to a different value than sessionId:%s.", proposedPartitionKey, this.getSessionId()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } }
Looks like this is still not fixed. Why do we throw this exception when SEQUENCE and VALUE are now supported formats?
public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return BinaryData.fromBytes(amqpAnnotatedMessage.getBody().getFirstData()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new IllegalStateException("Message body type is not DATA, instead " + "it is: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
+ "it is: " + type.toString()));
public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return BinaryData.fromBytes(amqpAnnotatedMessage.getBody().getFirstData()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new IllegalStateException("Message body type is not DATA, instead " + "it is: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
class ServiceBusMessage { private static final int MAX_MESSAGE_ID_LENGTH = 128; private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final int MAX_SESSION_ID_LENGTH = 128; private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} with a {@link StandardCharsets * * @param body The content of the Service Bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into {@link * BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(body.toBytes())); } /** * This constructor provides an easy way to create {@link ServiceBusMessage} with message body as AMQP Data types * {@code SEQUENCE} and {@code VALUE}. It support sending and receiving of only one AMQP Sequence at present. * If you are sending message with single byte array or String data, you can also use other constructor. * * @param amqpMessageBody amqp message body. * * @throws NullPointerException if {@code amqpMessageBody} is {@code null}. */ public ServiceBusMessage(AmqpMessageBody amqpMessageBody) { Objects.requireNonNull(amqpMessageBody, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. * @throws IllegalStateException for invalid {@link AmqpMessageBodyType}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); final AmqpMessageBodyType bodyType = receivedMessage.getRawAmqpMessage().getBody().getBodyType(); AmqpMessageBody amqpMessageBody; switch (bodyType) { case DATA: amqpMessageBody = AmqpMessageBody.fromData(receivedMessage.getRawAmqpMessage().getBody() .getFirstData()); break; case SEQUENCE: amqpMessageBody = AmqpMessageBody.fromSequence(receivedMessage.getRawAmqpMessage().getBody() .getSequence()); break; case VALUE: amqpMessageBody = AmqpMessageBody.fromValue(receivedMessage.getRawAmqpMessage().getBody() .getValue()); break; default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); final AmqpMessageProperties receivedProperties = receivedMessage.getRawAmqpMessage().getProperties(); final AmqpMessageProperties newProperties = amqpAnnotatedMessage.getProperties(); newProperties.setMessageId(receivedProperties.getMessageId()); newProperties.setUserId(receivedProperties.getUserId()); newProperties.setTo(receivedProperties.getTo()); newProperties.setSubject(receivedProperties.getSubject()); newProperties.setReplyTo(receivedProperties.getReplyTo()); newProperties.setCorrelationId(receivedProperties.getCorrelationId()); newProperties.setContentType(receivedProperties.getContentType()); newProperties.setContentEncoding(receivedProperties.getContentEncoding()); newProperties.setAbsoluteExpiryTime(receivedProperties.getAbsoluteExpiryTime()); newProperties.setCreationTime(receivedProperties.getCreationTime()); newProperties.setGroupId(receivedProperties.getGroupId()); newProperties.setGroupSequence(receivedProperties.getGroupSequence()); newProperties.setReplyToGroupId(receivedProperties.getReplyToGroupId()); final AmqpMessageHeader receivedHeader = receivedMessage.getRawAmqpMessage().getHeader(); final AmqpMessageHeader newHeader = this.amqpAnnotatedMessage.getHeader(); newHeader.setPriority(receivedHeader.getPriority()); newHeader.setTimeToLive(receivedHeader.getTimeToLive()); newHeader.setDurable(receivedHeader.isDurable()); newHeader.setFirstAcquirer(receivedHeader.isFirstAcquirer()); final Map<String, Object> receivedAnnotations = receivedMessage.getRawAmqpMessage() .getMessageAnnotations(); final Map<String, Object> newAnnotations = this.amqpAnnotatedMessage.getMessageAnnotations(); for (Map.Entry<String, Object> entry : receivedAnnotations.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == LOCKED_UNTIL_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_TIME_UTC_ANNOTATION_NAME) { continue; } newAnnotations.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedDelivery = receivedMessage.getRawAmqpMessage().getDeliveryAnnotations(); final Map<String, Object> newDelivery = this.amqpAnnotatedMessage.getDeliveryAnnotations(); for (Map.Entry<String, Object> entry : receivedDelivery.entrySet()) { newDelivery.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedFooter = receivedMessage.getRawAmqpMessage().getFooter(); final Map<String, Object> newFooter = this.amqpAnnotatedMessage.getFooter(); for (Map.Entry<String, Object> entry : receivedFooter.entrySet()) { newFooter.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedApplicationProperties = receivedMessage.getRawAmqpMessage() .getApplicationProperties(); final Map<String, Object> newApplicationProperties = this.amqpAnnotatedMessage.getApplicationProperties(); for (Map.Entry<String, Object> entry : receivedApplicationProperties.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_REASON_ANNOTATION_NAME) { continue; } newApplicationProperties.put(entry.getKey(), entry.getValue()); } this.context = Context.NONE; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code * getApplicationProperties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides convenience APIs to serialize/deserialize the object.</p> * * <p>If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use * of {@link * consumers who wish to deserialize the binary data.</p> * * @throws IllegalStateException if called for the messages which are not of binary data type. * @return Binary data representing the payload. */ /** * Gets the content type of the message. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * @return The content type of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * * @param contentType RFC2045 Content-Type descriptor of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return The correlation id of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { String correlationId = null; AmqpMessageId amqpCorrelationId = amqpAnnotatedMessage.getProperties().getCorrelationId(); if (amqpCorrelationId != null) { correlationId = amqpCorrelationId.toString(); } return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { AmqpMessageId id = null; if (correlationId != null) { id = new AmqpMessageId(correlationId); } amqpAnnotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the subject for the message. * * <p> * This property enables the application to indicate the purpose of the message to the receiver in a standardized * fashion, similar to an email subject line. The mapped AMQP property is "subject". * </p> * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The application specific subject. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If * enabled, the * <a href="https: * feature identifies and removes second and further submissions of messages with the same {@code messageId}. * </p> * * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { String messageId = null; AmqpMessageId amqpMessageId = amqpAnnotatedMessage.getProperties().getMessageId(); if (amqpMessageId != null) { messageId = amqpMessageId.toString(); } return messageId; } /** * Sets the message id. * * @param messageId The message id to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public ServiceBusMessage setMessageId(String messageId) { checkIdLength("messageId", messageId, MAX_MESSAGE_ID_LENGTH); AmqpMessageId id = null; if (messageId != null) { id = new AmqpMessageId(messageId); } amqpAnnotatedMessage.getProperties().setMessageId(id); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * </p> * * @return The partition key of this message. * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey The partition key of this message. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code partitionKey} is too long or if the {@code partitionKey} does not * match the {@code sessionId}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { checkIdLength("partitionKey", partitionKey, MAX_PARTITION_KEY_LENGTH); checkPartitionKey(partitionKey); amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return The raw AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return amqpAnnotatedMessage; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { String replyTo = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getReplyTo(); if (amqpAddress != null) { replyTo = amqpAddress.toString(); } return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { AmqpAddress replyToAddress = null; if (replyTo != null) { replyToAddress = new AmqpAddress(replyTo); } amqpAnnotatedMessage.getProperties().setReplyTo(replyToAddress); return this; } /** * Gets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @return "To" property value of this message */ public String getTo() { String to = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getTo(); if (amqpAddress != null) { to = amqpAddress.toString(); } return to; } /** * Sets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @param to To property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { AmqpAddress toAddress = null; if (to != null) { toAddress = new AmqpAddress(to); } amqpAnnotatedMessage.getProperties().setTo(toAddress); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the {@link * be set for the reply when sent to the reply entity. * * @return The {@code getReplyToGroupId} property value of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId The ReplyToGroupId property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the session identifier for a session-aware entity. * * <p> * For session-aware entities, this application-defined value specifies the session affiliation of the message. * Messages with the same session identifier are subject to summary locking and enable exact in-order processing and * demultiplexing. For session-unaware entities, this value is ignored. See <a * href="https: * </p> * * @return The session id of the {@link ServiceBusMessage}. * @see <a href="https: */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session identifier for a session-aware entity. * * @param sessionId The session identifier to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code sessionId} is too long or if the {@code sessionId} does not match * the {@code partitionKey}. */ public ServiceBusMessage setSessionId(String sessionId) { checkIdLength("sessionId", sessionId, MAX_SESSION_ID_LENGTH); checkSessionId(sessionId); amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /** * Checks the length of ID fields. * * Some fields within the message will cause a failure in the service without enough context information. */ private void checkIdLength(String fieldName, String value, int maxLength) { if (value != null && value.length() > maxLength) { final String message = String.format("%s cannot be longer than %d characters.", fieldName, maxLength); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkSessionId(String proposedSessionId) { if (proposedSessionId == null) { return; } if (this.getPartitionKey() != null && this.getPartitionKey().compareTo(proposedSessionId) != 0) { final String message = String.format( "sessionId:%s cannot be set to a different value than partitionKey:%s.", proposedSessionId, this.getPartitionKey()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkPartitionKey(String proposedPartitionKey) { if (proposedPartitionKey == null) { return; } if (this.getSessionId() != null && this.getSessionId().compareTo(proposedPartitionKey) != 0) { final String message = String.format( "partitionKey:%s cannot be set to a different value than sessionId:%s.", proposedPartitionKey, this.getSessionId()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } }
class ServiceBusMessage { private static final int MAX_MESSAGE_ID_LENGTH = 128; private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final int MAX_SESSION_ID_LENGTH = 128; private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} with a {@link StandardCharsets * * @param body The content of the Service Bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into {@link * BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(body.toBytes())); } /** * This constructor provides an easy way to create {@link ServiceBusMessage} with message body as AMQP Data types * {@code SEQUENCE} and {@code VALUE}. * In case of {@code SEQUENCE}, tt support sending and receiving of only one AMQP Sequence at present. * If you are sending message with single byte array or String data, you can also use other constructor. * * @param amqpMessageBody amqp message body. * * @throws NullPointerException if {@code amqpMessageBody} is {@code null}. */ public ServiceBusMessage(AmqpMessageBody amqpMessageBody) { Objects.requireNonNull(amqpMessageBody, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. * @throws IllegalStateException for invalid {@link AmqpMessageBodyType}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); final AmqpMessageBodyType bodyType = receivedMessage.getRawAmqpMessage().getBody().getBodyType(); AmqpMessageBody amqpMessageBody; switch (bodyType) { case DATA: amqpMessageBody = AmqpMessageBody.fromData(receivedMessage.getRawAmqpMessage().getBody() .getFirstData()); break; case SEQUENCE: amqpMessageBody = AmqpMessageBody.fromSequence(receivedMessage.getRawAmqpMessage().getBody() .getSequence()); break; case VALUE: amqpMessageBody = AmqpMessageBody.fromValue(receivedMessage.getRawAmqpMessage().getBody() .getValue()); break; default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); final AmqpMessageProperties receivedProperties = receivedMessage.getRawAmqpMessage().getProperties(); final AmqpMessageProperties newProperties = amqpAnnotatedMessage.getProperties(); newProperties.setMessageId(receivedProperties.getMessageId()); newProperties.setUserId(receivedProperties.getUserId()); newProperties.setTo(receivedProperties.getTo()); newProperties.setSubject(receivedProperties.getSubject()); newProperties.setReplyTo(receivedProperties.getReplyTo()); newProperties.setCorrelationId(receivedProperties.getCorrelationId()); newProperties.setContentType(receivedProperties.getContentType()); newProperties.setContentEncoding(receivedProperties.getContentEncoding()); newProperties.setAbsoluteExpiryTime(receivedProperties.getAbsoluteExpiryTime()); newProperties.setCreationTime(receivedProperties.getCreationTime()); newProperties.setGroupId(receivedProperties.getGroupId()); newProperties.setGroupSequence(receivedProperties.getGroupSequence()); newProperties.setReplyToGroupId(receivedProperties.getReplyToGroupId()); final AmqpMessageHeader receivedHeader = receivedMessage.getRawAmqpMessage().getHeader(); final AmqpMessageHeader newHeader = this.amqpAnnotatedMessage.getHeader(); newHeader.setPriority(receivedHeader.getPriority()); newHeader.setTimeToLive(receivedHeader.getTimeToLive()); newHeader.setDurable(receivedHeader.isDurable()); newHeader.setFirstAcquirer(receivedHeader.isFirstAcquirer()); final Map<String, Object> receivedAnnotations = receivedMessage.getRawAmqpMessage() .getMessageAnnotations(); final Map<String, Object> newAnnotations = this.amqpAnnotatedMessage.getMessageAnnotations(); for (Map.Entry<String, Object> entry : receivedAnnotations.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == LOCKED_UNTIL_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_TIME_UTC_ANNOTATION_NAME) { continue; } newAnnotations.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedDelivery = receivedMessage.getRawAmqpMessage().getDeliveryAnnotations(); final Map<String, Object> newDelivery = this.amqpAnnotatedMessage.getDeliveryAnnotations(); for (Map.Entry<String, Object> entry : receivedDelivery.entrySet()) { newDelivery.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedFooter = receivedMessage.getRawAmqpMessage().getFooter(); final Map<String, Object> newFooter = this.amqpAnnotatedMessage.getFooter(); for (Map.Entry<String, Object> entry : receivedFooter.entrySet()) { newFooter.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedApplicationProperties = receivedMessage.getRawAmqpMessage() .getApplicationProperties(); final Map<String, Object> newApplicationProperties = this.amqpAnnotatedMessage.getApplicationProperties(); for (Map.Entry<String, Object> entry : receivedApplicationProperties.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_REASON_ANNOTATION_NAME) { continue; } newApplicationProperties.put(entry.getKey(), entry.getValue()); } this.context = Context.NONE; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code * getApplicationProperties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides convenience APIs to serialize/deserialize the object.</p> * * <p>If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use * of {@link * consumers who wish to deserialize the binary data.</p> * * @throws IllegalStateException if called for the messages which are not of binary data type. * @return Binary data representing the payload. */ /** * Gets the content type of the message. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * @return The content type of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * * @param contentType RFC2045 Content-Type descriptor of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return The correlation id of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { String correlationId = null; AmqpMessageId amqpCorrelationId = amqpAnnotatedMessage.getProperties().getCorrelationId(); if (amqpCorrelationId != null) { correlationId = amqpCorrelationId.toString(); } return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { AmqpMessageId id = null; if (correlationId != null) { id = new AmqpMessageId(correlationId); } amqpAnnotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the subject for the message. * * <p> * This property enables the application to indicate the purpose of the message to the receiver in a standardized * fashion, similar to an email subject line. The mapped AMQP property is "subject". * </p> * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The application specific subject. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If * enabled, the * <a href="https: * feature identifies and removes second and further submissions of messages with the same {@code messageId}. * </p> * * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { String messageId = null; AmqpMessageId amqpMessageId = amqpAnnotatedMessage.getProperties().getMessageId(); if (amqpMessageId != null) { messageId = amqpMessageId.toString(); } return messageId; } /** * Sets the message id. * * @param messageId The message id to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public ServiceBusMessage setMessageId(String messageId) { checkIdLength("messageId", messageId, MAX_MESSAGE_ID_LENGTH); AmqpMessageId id = null; if (messageId != null) { id = new AmqpMessageId(messageId); } amqpAnnotatedMessage.getProperties().setMessageId(id); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * </p> * * @return The partition key of this message. * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey The partition key of this message. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code partitionKey} is too long or if the {@code partitionKey} does not * match the {@code sessionId}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { checkIdLength("partitionKey", partitionKey, MAX_PARTITION_KEY_LENGTH); checkPartitionKey(partitionKey); amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return The raw AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return amqpAnnotatedMessage; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { String replyTo = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getReplyTo(); if (amqpAddress != null) { replyTo = amqpAddress.toString(); } return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { AmqpAddress replyToAddress = null; if (replyTo != null) { replyToAddress = new AmqpAddress(replyTo); } amqpAnnotatedMessage.getProperties().setReplyTo(replyToAddress); return this; } /** * Gets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @return "To" property value of this message */ public String getTo() { String to = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getTo(); if (amqpAddress != null) { to = amqpAddress.toString(); } return to; } /** * Sets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @param to To property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { AmqpAddress toAddress = null; if (to != null) { toAddress = new AmqpAddress(to); } amqpAnnotatedMessage.getProperties().setTo(toAddress); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the {@link * be set for the reply when sent to the reply entity. * * @return The {@code getReplyToGroupId} property value of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId The ReplyToGroupId property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the session identifier for a session-aware entity. * * <p> * For session-aware entities, this application-defined value specifies the session affiliation of the message. * Messages with the same session identifier are subject to summary locking and enable exact in-order processing and * demultiplexing. For session-unaware entities, this value is ignored. See <a * href="https: * </p> * * @return The session id of the {@link ServiceBusMessage}. * @see <a href="https: */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session identifier for a session-aware entity. * * @param sessionId The session identifier to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code sessionId} is too long or if the {@code sessionId} does not match * the {@code partitionKey}. */ public ServiceBusMessage setSessionId(String sessionId) { checkIdLength("sessionId", sessionId, MAX_SESSION_ID_LENGTH); checkSessionId(sessionId); amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /** * Checks the length of ID fields. * * Some fields within the message will cause a failure in the service without enough context information. */ private void checkIdLength(String fieldName, String value, int maxLength) { if (value != null && value.length() > maxLength) { final String message = String.format("%s cannot be longer than %d characters.", fieldName, maxLength); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkSessionId(String proposedSessionId) { if (proposedSessionId == null) { return; } if (this.getPartitionKey() != null && this.getPartitionKey().compareTo(proposedSessionId) != 0) { final String message = String.format( "sessionId:%s cannot be set to a different value than partitionKey:%s.", proposedSessionId, this.getPartitionKey()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkPartitionKey(String proposedPartitionKey) { if (proposedPartitionKey == null) { return; } if (this.getSessionId() != null && this.getSessionId().compareTo(proposedPartitionKey) != 0) { final String message = String.format( "partitionKey:%s cannot be set to a different value than sessionId:%s.", proposedPartitionKey, this.getSessionId()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } }
This method `getBody()` represents AMQP Type `DATA` . If the message body type is `SEQUENCE` or `VALUE`, user should call `getSequence()` and `getValue()`on `AmqpMessgeBody`. So here we still need to throw this error.
public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return BinaryData.fromBytes(amqpAnnotatedMessage.getBody().getFirstData()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new IllegalStateException("Message body type is not DATA, instead " + "it is: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
+ "it is: " + type.toString()));
public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return BinaryData.fromBytes(amqpAnnotatedMessage.getBody().getFirstData()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new IllegalStateException("Message body type is not DATA, instead " + "it is: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
class ServiceBusMessage { private static final int MAX_MESSAGE_ID_LENGTH = 128; private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final int MAX_SESSION_ID_LENGTH = 128; private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} with a {@link StandardCharsets * * @param body The content of the Service Bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into {@link * BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(body.toBytes())); } /** * This constructor provides an easy way to create {@link ServiceBusMessage} with message body as AMQP Data types * {@code SEQUENCE} and {@code VALUE}. It support sending and receiving of only one AMQP Sequence at present. * If you are sending message with single byte array or String data, you can also use other constructor. * * @param amqpMessageBody amqp message body. * * @throws NullPointerException if {@code amqpMessageBody} is {@code null}. */ public ServiceBusMessage(AmqpMessageBody amqpMessageBody) { Objects.requireNonNull(amqpMessageBody, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. * @throws IllegalStateException for invalid {@link AmqpMessageBodyType}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); final AmqpMessageBodyType bodyType = receivedMessage.getRawAmqpMessage().getBody().getBodyType(); AmqpMessageBody amqpMessageBody; switch (bodyType) { case DATA: amqpMessageBody = AmqpMessageBody.fromData(receivedMessage.getRawAmqpMessage().getBody() .getFirstData()); break; case SEQUENCE: amqpMessageBody = AmqpMessageBody.fromSequence(receivedMessage.getRawAmqpMessage().getBody() .getSequence()); break; case VALUE: amqpMessageBody = AmqpMessageBody.fromValue(receivedMessage.getRawAmqpMessage().getBody() .getValue()); break; default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); final AmqpMessageProperties receivedProperties = receivedMessage.getRawAmqpMessage().getProperties(); final AmqpMessageProperties newProperties = amqpAnnotatedMessage.getProperties(); newProperties.setMessageId(receivedProperties.getMessageId()); newProperties.setUserId(receivedProperties.getUserId()); newProperties.setTo(receivedProperties.getTo()); newProperties.setSubject(receivedProperties.getSubject()); newProperties.setReplyTo(receivedProperties.getReplyTo()); newProperties.setCorrelationId(receivedProperties.getCorrelationId()); newProperties.setContentType(receivedProperties.getContentType()); newProperties.setContentEncoding(receivedProperties.getContentEncoding()); newProperties.setAbsoluteExpiryTime(receivedProperties.getAbsoluteExpiryTime()); newProperties.setCreationTime(receivedProperties.getCreationTime()); newProperties.setGroupId(receivedProperties.getGroupId()); newProperties.setGroupSequence(receivedProperties.getGroupSequence()); newProperties.setReplyToGroupId(receivedProperties.getReplyToGroupId()); final AmqpMessageHeader receivedHeader = receivedMessage.getRawAmqpMessage().getHeader(); final AmqpMessageHeader newHeader = this.amqpAnnotatedMessage.getHeader(); newHeader.setPriority(receivedHeader.getPriority()); newHeader.setTimeToLive(receivedHeader.getTimeToLive()); newHeader.setDurable(receivedHeader.isDurable()); newHeader.setFirstAcquirer(receivedHeader.isFirstAcquirer()); final Map<String, Object> receivedAnnotations = receivedMessage.getRawAmqpMessage() .getMessageAnnotations(); final Map<String, Object> newAnnotations = this.amqpAnnotatedMessage.getMessageAnnotations(); for (Map.Entry<String, Object> entry : receivedAnnotations.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == LOCKED_UNTIL_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_TIME_UTC_ANNOTATION_NAME) { continue; } newAnnotations.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedDelivery = receivedMessage.getRawAmqpMessage().getDeliveryAnnotations(); final Map<String, Object> newDelivery = this.amqpAnnotatedMessage.getDeliveryAnnotations(); for (Map.Entry<String, Object> entry : receivedDelivery.entrySet()) { newDelivery.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedFooter = receivedMessage.getRawAmqpMessage().getFooter(); final Map<String, Object> newFooter = this.amqpAnnotatedMessage.getFooter(); for (Map.Entry<String, Object> entry : receivedFooter.entrySet()) { newFooter.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedApplicationProperties = receivedMessage.getRawAmqpMessage() .getApplicationProperties(); final Map<String, Object> newApplicationProperties = this.amqpAnnotatedMessage.getApplicationProperties(); for (Map.Entry<String, Object> entry : receivedApplicationProperties.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_REASON_ANNOTATION_NAME) { continue; } newApplicationProperties.put(entry.getKey(), entry.getValue()); } this.context = Context.NONE; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code * getApplicationProperties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides convenience APIs to serialize/deserialize the object.</p> * * <p>If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use * of {@link * consumers who wish to deserialize the binary data.</p> * * @throws IllegalStateException if called for the messages which are not of binary data type. * @return Binary data representing the payload. */ /** * Gets the content type of the message. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * @return The content type of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * * @param contentType RFC2045 Content-Type descriptor of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return The correlation id of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { String correlationId = null; AmqpMessageId amqpCorrelationId = amqpAnnotatedMessage.getProperties().getCorrelationId(); if (amqpCorrelationId != null) { correlationId = amqpCorrelationId.toString(); } return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { AmqpMessageId id = null; if (correlationId != null) { id = new AmqpMessageId(correlationId); } amqpAnnotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the subject for the message. * * <p> * This property enables the application to indicate the purpose of the message to the receiver in a standardized * fashion, similar to an email subject line. The mapped AMQP property is "subject". * </p> * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The application specific subject. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If * enabled, the * <a href="https: * feature identifies and removes second and further submissions of messages with the same {@code messageId}. * </p> * * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { String messageId = null; AmqpMessageId amqpMessageId = amqpAnnotatedMessage.getProperties().getMessageId(); if (amqpMessageId != null) { messageId = amqpMessageId.toString(); } return messageId; } /** * Sets the message id. * * @param messageId The message id to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public ServiceBusMessage setMessageId(String messageId) { checkIdLength("messageId", messageId, MAX_MESSAGE_ID_LENGTH); AmqpMessageId id = null; if (messageId != null) { id = new AmqpMessageId(messageId); } amqpAnnotatedMessage.getProperties().setMessageId(id); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * </p> * * @return The partition key of this message. * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey The partition key of this message. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code partitionKey} is too long or if the {@code partitionKey} does not * match the {@code sessionId}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { checkIdLength("partitionKey", partitionKey, MAX_PARTITION_KEY_LENGTH); checkPartitionKey(partitionKey); amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return The raw AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return amqpAnnotatedMessage; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { String replyTo = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getReplyTo(); if (amqpAddress != null) { replyTo = amqpAddress.toString(); } return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { AmqpAddress replyToAddress = null; if (replyTo != null) { replyToAddress = new AmqpAddress(replyTo); } amqpAnnotatedMessage.getProperties().setReplyTo(replyToAddress); return this; } /** * Gets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @return "To" property value of this message */ public String getTo() { String to = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getTo(); if (amqpAddress != null) { to = amqpAddress.toString(); } return to; } /** * Sets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @param to To property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { AmqpAddress toAddress = null; if (to != null) { toAddress = new AmqpAddress(to); } amqpAnnotatedMessage.getProperties().setTo(toAddress); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the {@link * be set for the reply when sent to the reply entity. * * @return The {@code getReplyToGroupId} property value of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId The ReplyToGroupId property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the session identifier for a session-aware entity. * * <p> * For session-aware entities, this application-defined value specifies the session affiliation of the message. * Messages with the same session identifier are subject to summary locking and enable exact in-order processing and * demultiplexing. For session-unaware entities, this value is ignored. See <a * href="https: * </p> * * @return The session id of the {@link ServiceBusMessage}. * @see <a href="https: */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session identifier for a session-aware entity. * * @param sessionId The session identifier to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code sessionId} is too long or if the {@code sessionId} does not match * the {@code partitionKey}. */ public ServiceBusMessage setSessionId(String sessionId) { checkIdLength("sessionId", sessionId, MAX_SESSION_ID_LENGTH); checkSessionId(sessionId); amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /** * Checks the length of ID fields. * * Some fields within the message will cause a failure in the service without enough context information. */ private void checkIdLength(String fieldName, String value, int maxLength) { if (value != null && value.length() > maxLength) { final String message = String.format("%s cannot be longer than %d characters.", fieldName, maxLength); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkSessionId(String proposedSessionId) { if (proposedSessionId == null) { return; } if (this.getPartitionKey() != null && this.getPartitionKey().compareTo(proposedSessionId) != 0) { final String message = String.format( "sessionId:%s cannot be set to a different value than partitionKey:%s.", proposedSessionId, this.getPartitionKey()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkPartitionKey(String proposedPartitionKey) { if (proposedPartitionKey == null) { return; } if (this.getSessionId() != null && this.getSessionId().compareTo(proposedPartitionKey) != 0) { final String message = String.format( "partitionKey:%s cannot be set to a different value than sessionId:%s.", proposedPartitionKey, this.getSessionId()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } }
class ServiceBusMessage { private static final int MAX_MESSAGE_ID_LENGTH = 128; private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final int MAX_SESSION_ID_LENGTH = 128; private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} with a {@link StandardCharsets * * @param body The content of the Service Bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into {@link * BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(body.toBytes())); } /** * This constructor provides an easy way to create {@link ServiceBusMessage} with message body as AMQP Data types * {@code SEQUENCE} and {@code VALUE}. * In case of {@code SEQUENCE}, tt support sending and receiving of only one AMQP Sequence at present. * If you are sending message with single byte array or String data, you can also use other constructor. * * @param amqpMessageBody amqp message body. * * @throws NullPointerException if {@code amqpMessageBody} is {@code null}. */ public ServiceBusMessage(AmqpMessageBody amqpMessageBody) { Objects.requireNonNull(amqpMessageBody, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. * @throws IllegalStateException for invalid {@link AmqpMessageBodyType}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); final AmqpMessageBodyType bodyType = receivedMessage.getRawAmqpMessage().getBody().getBodyType(); AmqpMessageBody amqpMessageBody; switch (bodyType) { case DATA: amqpMessageBody = AmqpMessageBody.fromData(receivedMessage.getRawAmqpMessage().getBody() .getFirstData()); break; case SEQUENCE: amqpMessageBody = AmqpMessageBody.fromSequence(receivedMessage.getRawAmqpMessage().getBody() .getSequence()); break; case VALUE: amqpMessageBody = AmqpMessageBody.fromValue(receivedMessage.getRawAmqpMessage().getBody() .getValue()); break; default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(amqpMessageBody); final AmqpMessageProperties receivedProperties = receivedMessage.getRawAmqpMessage().getProperties(); final AmqpMessageProperties newProperties = amqpAnnotatedMessage.getProperties(); newProperties.setMessageId(receivedProperties.getMessageId()); newProperties.setUserId(receivedProperties.getUserId()); newProperties.setTo(receivedProperties.getTo()); newProperties.setSubject(receivedProperties.getSubject()); newProperties.setReplyTo(receivedProperties.getReplyTo()); newProperties.setCorrelationId(receivedProperties.getCorrelationId()); newProperties.setContentType(receivedProperties.getContentType()); newProperties.setContentEncoding(receivedProperties.getContentEncoding()); newProperties.setAbsoluteExpiryTime(receivedProperties.getAbsoluteExpiryTime()); newProperties.setCreationTime(receivedProperties.getCreationTime()); newProperties.setGroupId(receivedProperties.getGroupId()); newProperties.setGroupSequence(receivedProperties.getGroupSequence()); newProperties.setReplyToGroupId(receivedProperties.getReplyToGroupId()); final AmqpMessageHeader receivedHeader = receivedMessage.getRawAmqpMessage().getHeader(); final AmqpMessageHeader newHeader = this.amqpAnnotatedMessage.getHeader(); newHeader.setPriority(receivedHeader.getPriority()); newHeader.setTimeToLive(receivedHeader.getTimeToLive()); newHeader.setDurable(receivedHeader.isDurable()); newHeader.setFirstAcquirer(receivedHeader.isFirstAcquirer()); final Map<String, Object> receivedAnnotations = receivedMessage.getRawAmqpMessage() .getMessageAnnotations(); final Map<String, Object> newAnnotations = this.amqpAnnotatedMessage.getMessageAnnotations(); for (Map.Entry<String, Object> entry : receivedAnnotations.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == LOCKED_UNTIL_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == ENQUEUED_TIME_UTC_ANNOTATION_NAME) { continue; } newAnnotations.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedDelivery = receivedMessage.getRawAmqpMessage().getDeliveryAnnotations(); final Map<String, Object> newDelivery = this.amqpAnnotatedMessage.getDeliveryAnnotations(); for (Map.Entry<String, Object> entry : receivedDelivery.entrySet()) { newDelivery.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedFooter = receivedMessage.getRawAmqpMessage().getFooter(); final Map<String, Object> newFooter = this.amqpAnnotatedMessage.getFooter(); for (Map.Entry<String, Object> entry : receivedFooter.entrySet()) { newFooter.put(entry.getKey(), entry.getValue()); } final Map<String, Object> receivedApplicationProperties = receivedMessage.getRawAmqpMessage() .getApplicationProperties(); final Map<String, Object> newApplicationProperties = this.amqpAnnotatedMessage.getApplicationProperties(); for (Map.Entry<String, Object> entry : receivedApplicationProperties.entrySet()) { if (AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME || AmqpMessageConstant.fromString(entry.getKey()) == DEAD_LETTER_REASON_ANNOTATION_NAME) { continue; } newApplicationProperties.put(entry.getKey(), entry.getValue()); } this.context = Context.NONE; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code * getApplicationProperties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides convenience APIs to serialize/deserialize the object.</p> * * <p>If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use * of {@link * consumers who wish to deserialize the binary data.</p> * * @throws IllegalStateException if called for the messages which are not of binary data type. * @return Binary data representing the payload. */ /** * Gets the content type of the message. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * @return The content type of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * * @param contentType RFC2045 Content-Type descriptor of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return The correlation id of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { String correlationId = null; AmqpMessageId amqpCorrelationId = amqpAnnotatedMessage.getProperties().getCorrelationId(); if (amqpCorrelationId != null) { correlationId = amqpCorrelationId.toString(); } return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { AmqpMessageId id = null; if (correlationId != null) { id = new AmqpMessageId(correlationId); } amqpAnnotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the subject for the message. * * <p> * This property enables the application to indicate the purpose of the message to the receiver in a standardized * fashion, similar to an email subject line. The mapped AMQP property is "subject". * </p> * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The application specific subject. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If * enabled, the * <a href="https: * feature identifies and removes second and further submissions of messages with the same {@code messageId}. * </p> * * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { String messageId = null; AmqpMessageId amqpMessageId = amqpAnnotatedMessage.getProperties().getMessageId(); if (amqpMessageId != null) { messageId = amqpMessageId.toString(); } return messageId; } /** * Sets the message id. * * @param messageId The message id to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public ServiceBusMessage setMessageId(String messageId) { checkIdLength("messageId", messageId, MAX_MESSAGE_ID_LENGTH); AmqpMessageId id = null; if (messageId != null) { id = new AmqpMessageId(messageId); } amqpAnnotatedMessage.getProperties().setMessageId(id); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * </p> * * @return The partition key of this message. * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey The partition key of this message. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code partitionKey} is too long or if the {@code partitionKey} does not * match the {@code sessionId}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { checkIdLength("partitionKey", partitionKey, MAX_PARTITION_KEY_LENGTH); checkPartitionKey(partitionKey); amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return The raw AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return amqpAnnotatedMessage; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { String replyTo = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getReplyTo(); if (amqpAddress != null) { replyTo = amqpAddress.toString(); } return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { AmqpAddress replyToAddress = null; if (replyTo != null) { replyToAddress = new AmqpAddress(replyTo); } amqpAnnotatedMessage.getProperties().setReplyTo(replyToAddress); return this; } /** * Gets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @return "To" property value of this message */ public String getTo() { String to = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getTo(); if (amqpAddress != null) { to = amqpAddress.toString(); } return to; } /** * Sets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * </p> * * @param to To property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { AmqpAddress toAddress = null; if (to != null) { toAddress = new AmqpAddress(to); } amqpAnnotatedMessage.getProperties().setTo(toAddress); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the {@link * be set for the reply when sent to the reply entity. * * @return The {@code getReplyToGroupId} property value of this message. * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId The ReplyToGroupId property value of this message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the session identifier for a session-aware entity. * * <p> * For session-aware entities, this application-defined value specifies the session affiliation of the message. * Messages with the same session identifier are subject to summary locking and enable exact in-order processing and * demultiplexing. For session-unaware entities, this value is ignored. See <a * href="https: * </p> * * @return The session id of the {@link ServiceBusMessage}. * @see <a href="https: */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session identifier for a session-aware entity. * * @param sessionId The session identifier to be set. * * @return The updated {@link ServiceBusMessage}. * @throws IllegalArgumentException if {@code sessionId} is too long or if the {@code sessionId} does not match * the {@code partitionKey}. */ public ServiceBusMessage setSessionId(String sessionId) { checkIdLength("sessionId", sessionId, MAX_SESSION_ID_LENGTH); checkSessionId(sessionId); amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /** * Checks the length of ID fields. * * Some fields within the message will cause a failure in the service without enough context information. */ private void checkIdLength(String fieldName, String value, int maxLength) { if (value != null && value.length() > maxLength) { final String message = String.format("%s cannot be longer than %d characters.", fieldName, maxLength); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkSessionId(String proposedSessionId) { if (proposedSessionId == null) { return; } if (this.getPartitionKey() != null && this.getPartitionKey().compareTo(proposedSessionId) != 0) { final String message = String.format( "sessionId:%s cannot be set to a different value than partitionKey:%s.", proposedSessionId, this.getPartitionKey()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkPartitionKey(String proposedPartitionKey) { if (proposedPartitionKey == null) { return; } if (this.getSessionId() != null && this.getSessionId().compareTo(proposedPartitionKey) != 0) { final String message = String.format( "partitionKey:%s cannot be set to a different value than sessionId:%s.", proposedPartitionKey, this.getSessionId()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } }
I remember @ZhuXiaoBing-cn's PR has added a function for this comparison, please refactor accordingly.
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); ClientRegistration clientRegistration = context.getClientRegistration(); if (!AADAuthorizationGrantType.ON_BEHALF_OF.getValue().equals(clientRegistration.getAuthorizationGrantType().getValue())) { return null; } OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) { return null; } return loadOboAuthorizedClient(context.getClientRegistration(), context.getPrincipal()); }
if (!AADAuthorizationGrantType.ON_BEHALF_OF.getValue().equals(clientRegistration.getAuthorizationGrantType().getValue())) {
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); ClientRegistration clientRegistration = context.getClientRegistration(); if (!AADAuthorizationGrantType.ON_BEHALF_OF .isSameGrantType(clientRegistration.getAuthorizationGrantType())) { return null; } OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) { return null; } return getOboAuthorizedClient(context.getClientRegistration(), context.getPrincipal()); }
class AADOBOOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider { private static final Logger LOGGER = LoggerFactory.getLogger(AADOBOOAuth2AuthorizedClientProvider.class); private final Clock clock = Clock.systemUTC(); private final Duration clockSkew = Duration.ofSeconds(60); @Override private boolean hasTokenExpired(AbstractOAuth2Token token) { return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew)); } @SuppressWarnings({ "unchecked", "rawtypes" }) private <T extends OAuth2AuthorizedClient> T loadOboAuthorizedClient(ClientRegistration clientRegistration, Authentication principal) { if (!(principal instanceof AbstractOAuth2TokenAuthenticationToken)) { throw new IllegalStateException("Unsupported token implementation " + principal.getClass()); } try { String accessToken = ((AbstractOAuth2TokenAuthenticationToken<?>) principal).getToken() .getTokenValue(); OnBehalfOfParameters parameters = OnBehalfOfParameters .builder(clientRegistration.getScopes(), new UserAssertion(accessToken)) .build(); ConfidentialClientApplication clientApplication = createApp(clientRegistration); if (null == clientApplication) { return null; } String oboAccessToken = clientApplication.acquireToken(parameters).get().accessToken(); JWT parser = JWTParser.parse(oboAccessToken); Date iat = (Date) parser.getJWTClaimsSet().getClaim("iat"); Date exp = (Date) parser.getJWTClaimsSet().getClaim("exp"); OAuth2AccessToken oAuth2AccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, oboAccessToken, Instant.ofEpochMilli(iat.getTime()), Instant.ofEpochMilli(exp.getTime())); OAuth2AuthorizedClient oAuth2AuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, principal.getName(), oAuth2AccessToken); LOGGER.info("load obo authorized client success"); return (T) oAuth2AuthorizedClient; } catch (ExecutionException exception) { Optional.of(exception) .map(Throwable::getCause) .filter(e -> e instanceof MsalInteractionRequiredException) .map(e -> (MsalInteractionRequiredException) e) .ifPresent(this::replyForbiddenWithWwwAuthenticateHeader); LOGGER.error("Failed to load authorized client.", exception); } catch (InterruptedException | ParseException exception) { LOGGER.error("Failed to load authorized client.", exception); } return null; } ConfidentialClientApplication createApp(ClientRegistration clientRegistration) { String authorizationUri = clientRegistration.getProviderDetails().getAuthorizationUri(); String authority = interceptAuthorizationUri(authorizationUri); IClientSecret clientCredential = ClientCredentialFactory .createFromSecret(clientRegistration.getClientSecret()); try { return ConfidentialClientApplication.builder(clientRegistration.getClientId(), clientCredential) .authority(authority) .build(); } catch (MalformedURLException e) { LOGGER.error("Failed to create ConfidentialClientApplication", e); } return null; } private String interceptAuthorizationUri(String authorizationUri) { int count = 0; int slashNumber = 4; for (int i = 0; i < authorizationUri.length(); i++) { if (authorizationUri.charAt(i) == '/') { count++; } if (count == slashNumber) { return authorizationUri.substring(0, i + 1); } } return null; } private void replyForbiddenWithWwwAuthenticateHeader(MsalInteractionRequiredException exception) { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletResponse response = attr.getResponse(); Assert.notNull(response, "HttpServletResponse should not be null."); response.setStatus(HttpStatus.FORBIDDEN.value()); Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put(Constants.CONDITIONAL_ACCESS_POLICY_CLAIMS, exception.claims()); parameters.put(OAuth2ParameterNames.ERROR, OAuth2ErrorCodes.INVALID_TOKEN); parameters.put(OAuth2ParameterNames.ERROR_DESCRIPTION, "The resource server requires higher privileges " + "than " + "provided by the access token"); response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Constants.BEARER_PREFIX + parameters.toString()); } }
class AADOBOOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider { private static final Logger LOGGER = LoggerFactory.getLogger(AADOBOOAuth2AuthorizedClientProvider.class); private final Clock clock = Clock.systemUTC(); private final Duration clockSkew = Duration.ofSeconds(60); @Override private boolean hasTokenExpired(AbstractOAuth2Token token) { Instant expiresAt = token.getExpiresAt(); if (expiresAt == null) { return true; } expiresAt = expiresAt.minus(this.clockSkew); return this.clock.instant().isAfter(expiresAt); } @SuppressWarnings({ "unchecked", "rawtypes" }) private <T extends OAuth2AuthorizedClient> T getOboAuthorizedClient(ClientRegistration clientRegistration, Authentication principal) { if (!(principal instanceof AbstractOAuth2TokenAuthenticationToken)) { throw new IllegalStateException("Unsupported token implementation " + principal.getClass()); } try { String accessToken = ((AbstractOAuth2TokenAuthenticationToken<?>) principal).getToken() .getTokenValue(); OnBehalfOfParameters parameters = OnBehalfOfParameters .builder(clientRegistration.getScopes(), new UserAssertion(accessToken)) .build(); ConfidentialClientApplication clientApplication = createApp(clientRegistration); if (null == clientApplication) { return null; } String oboAccessToken = clientApplication.acquireToken(parameters).get().accessToken(); JWT parser = JWTParser.parse(oboAccessToken); Date iat = (Date) parser.getJWTClaimsSet().getClaim("iat"); Date exp = (Date) parser.getJWTClaimsSet().getClaim("exp"); OAuth2AccessToken oAuth2AccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, oboAccessToken, Instant.ofEpochMilli(iat.getTime()), Instant.ofEpochMilli(exp.getTime())); OAuth2AuthorizedClient oAuth2AuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, principal.getName(), oAuth2AccessToken); LOGGER.info("load obo authorized client success"); return (T) oAuth2AuthorizedClient; } catch (ExecutionException exception) { Optional.of(exception) .map(Throwable::getCause) .filter(e -> e instanceof MsalInteractionRequiredException) .map(e -> (MsalInteractionRequiredException) e) .map(MsalServiceException::claims) .filter(StringUtils::hasText) .ifPresent(this::replyForbiddenWithWwwAuthenticateHeader); LOGGER.error("Failed to load authorized client.", exception); } catch (InterruptedException | ParseException exception) { LOGGER.error("Failed to load authorized client.", exception); } return null; } ConfidentialClientApplication createApp(ClientRegistration clientRegistration) { String authorizationUri = clientRegistration.getProviderDetails().getAuthorizationUri(); String authority = interceptAuthorizationUri(authorizationUri); IClientSecret clientCredential = ClientCredentialFactory .createFromSecret(clientRegistration.getClientSecret()); try { return ConfidentialClientApplication.builder(clientRegistration.getClientId(), clientCredential) .authority(authority) .build(); } catch (MalformedURLException e) { LOGGER.error("Failed to create ConfidentialClientApplication", e); } return null; } private String interceptAuthorizationUri(String authorizationUri) { int count = 0; int slashNumber = 4; for (int i = 0; i < authorizationUri.length(); i++) { if (authorizationUri.charAt(i) == '/') { count++; } if (count == slashNumber) { return authorizationUri.substring(0, i + 1); } } return null; } private void replyForbiddenWithWwwAuthenticateHeader(String claims) { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletResponse response = attr.getResponse(); Assert.notNull(response, "HttpServletResponse should not be null."); response.setStatus(HttpStatus.FORBIDDEN.value()); Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put(Constants.CONDITIONAL_ACCESS_POLICY_CLAIMS, claims); parameters.put(OAuth2ParameterNames.ERROR, OAuth2ErrorCodes.INVALID_TOKEN); parameters.put(OAuth2ParameterNames.ERROR_DESCRIPTION, "The resource server requires higher privileges " + "than " + "provided by the access token"); response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Constants.BEARER_PREFIX + parameters.toString()); } }
yes, I will do the refactor
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); ClientRegistration clientRegistration = context.getClientRegistration(); if (!AADAuthorizationGrantType.ON_BEHALF_OF.getValue().equals(clientRegistration.getAuthorizationGrantType().getValue())) { return null; } OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) { return null; } return loadOboAuthorizedClient(context.getClientRegistration(), context.getPrincipal()); }
if (!AADAuthorizationGrantType.ON_BEHALF_OF.getValue().equals(clientRegistration.getAuthorizationGrantType().getValue())) {
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); ClientRegistration clientRegistration = context.getClientRegistration(); if (!AADAuthorizationGrantType.ON_BEHALF_OF .isSameGrantType(clientRegistration.getAuthorizationGrantType())) { return null; } OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) { return null; } return getOboAuthorizedClient(context.getClientRegistration(), context.getPrincipal()); }
class AADOBOOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider { private static final Logger LOGGER = LoggerFactory.getLogger(AADOBOOAuth2AuthorizedClientProvider.class); private final Clock clock = Clock.systemUTC(); private final Duration clockSkew = Duration.ofSeconds(60); @Override private boolean hasTokenExpired(AbstractOAuth2Token token) { return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew)); } @SuppressWarnings({ "unchecked", "rawtypes" }) private <T extends OAuth2AuthorizedClient> T loadOboAuthorizedClient(ClientRegistration clientRegistration, Authentication principal) { if (!(principal instanceof AbstractOAuth2TokenAuthenticationToken)) { throw new IllegalStateException("Unsupported token implementation " + principal.getClass()); } try { String accessToken = ((AbstractOAuth2TokenAuthenticationToken<?>) principal).getToken() .getTokenValue(); OnBehalfOfParameters parameters = OnBehalfOfParameters .builder(clientRegistration.getScopes(), new UserAssertion(accessToken)) .build(); ConfidentialClientApplication clientApplication = createApp(clientRegistration); if (null == clientApplication) { return null; } String oboAccessToken = clientApplication.acquireToken(parameters).get().accessToken(); JWT parser = JWTParser.parse(oboAccessToken); Date iat = (Date) parser.getJWTClaimsSet().getClaim("iat"); Date exp = (Date) parser.getJWTClaimsSet().getClaim("exp"); OAuth2AccessToken oAuth2AccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, oboAccessToken, Instant.ofEpochMilli(iat.getTime()), Instant.ofEpochMilli(exp.getTime())); OAuth2AuthorizedClient oAuth2AuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, principal.getName(), oAuth2AccessToken); LOGGER.info("load obo authorized client success"); return (T) oAuth2AuthorizedClient; } catch (ExecutionException exception) { Optional.of(exception) .map(Throwable::getCause) .filter(e -> e instanceof MsalInteractionRequiredException) .map(e -> (MsalInteractionRequiredException) e) .ifPresent(this::replyForbiddenWithWwwAuthenticateHeader); LOGGER.error("Failed to load authorized client.", exception); } catch (InterruptedException | ParseException exception) { LOGGER.error("Failed to load authorized client.", exception); } return null; } ConfidentialClientApplication createApp(ClientRegistration clientRegistration) { String authorizationUri = clientRegistration.getProviderDetails().getAuthorizationUri(); String authority = interceptAuthorizationUri(authorizationUri); IClientSecret clientCredential = ClientCredentialFactory .createFromSecret(clientRegistration.getClientSecret()); try { return ConfidentialClientApplication.builder(clientRegistration.getClientId(), clientCredential) .authority(authority) .build(); } catch (MalformedURLException e) { LOGGER.error("Failed to create ConfidentialClientApplication", e); } return null; } private String interceptAuthorizationUri(String authorizationUri) { int count = 0; int slashNumber = 4; for (int i = 0; i < authorizationUri.length(); i++) { if (authorizationUri.charAt(i) == '/') { count++; } if (count == slashNumber) { return authorizationUri.substring(0, i + 1); } } return null; } private void replyForbiddenWithWwwAuthenticateHeader(MsalInteractionRequiredException exception) { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletResponse response = attr.getResponse(); Assert.notNull(response, "HttpServletResponse should not be null."); response.setStatus(HttpStatus.FORBIDDEN.value()); Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put(Constants.CONDITIONAL_ACCESS_POLICY_CLAIMS, exception.claims()); parameters.put(OAuth2ParameterNames.ERROR, OAuth2ErrorCodes.INVALID_TOKEN); parameters.put(OAuth2ParameterNames.ERROR_DESCRIPTION, "The resource server requires higher privileges " + "than " + "provided by the access token"); response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Constants.BEARER_PREFIX + parameters.toString()); } }
class AADOBOOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider { private static final Logger LOGGER = LoggerFactory.getLogger(AADOBOOAuth2AuthorizedClientProvider.class); private final Clock clock = Clock.systemUTC(); private final Duration clockSkew = Duration.ofSeconds(60); @Override private boolean hasTokenExpired(AbstractOAuth2Token token) { Instant expiresAt = token.getExpiresAt(); if (expiresAt == null) { return true; } expiresAt = expiresAt.minus(this.clockSkew); return this.clock.instant().isAfter(expiresAt); } @SuppressWarnings({ "unchecked", "rawtypes" }) private <T extends OAuth2AuthorizedClient> T getOboAuthorizedClient(ClientRegistration clientRegistration, Authentication principal) { if (!(principal instanceof AbstractOAuth2TokenAuthenticationToken)) { throw new IllegalStateException("Unsupported token implementation " + principal.getClass()); } try { String accessToken = ((AbstractOAuth2TokenAuthenticationToken<?>) principal).getToken() .getTokenValue(); OnBehalfOfParameters parameters = OnBehalfOfParameters .builder(clientRegistration.getScopes(), new UserAssertion(accessToken)) .build(); ConfidentialClientApplication clientApplication = createApp(clientRegistration); if (null == clientApplication) { return null; } String oboAccessToken = clientApplication.acquireToken(parameters).get().accessToken(); JWT parser = JWTParser.parse(oboAccessToken); Date iat = (Date) parser.getJWTClaimsSet().getClaim("iat"); Date exp = (Date) parser.getJWTClaimsSet().getClaim("exp"); OAuth2AccessToken oAuth2AccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, oboAccessToken, Instant.ofEpochMilli(iat.getTime()), Instant.ofEpochMilli(exp.getTime())); OAuth2AuthorizedClient oAuth2AuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, principal.getName(), oAuth2AccessToken); LOGGER.info("load obo authorized client success"); return (T) oAuth2AuthorizedClient; } catch (ExecutionException exception) { Optional.of(exception) .map(Throwable::getCause) .filter(e -> e instanceof MsalInteractionRequiredException) .map(e -> (MsalInteractionRequiredException) e) .map(MsalServiceException::claims) .filter(StringUtils::hasText) .ifPresent(this::replyForbiddenWithWwwAuthenticateHeader); LOGGER.error("Failed to load authorized client.", exception); } catch (InterruptedException | ParseException exception) { LOGGER.error("Failed to load authorized client.", exception); } return null; } ConfidentialClientApplication createApp(ClientRegistration clientRegistration) { String authorizationUri = clientRegistration.getProviderDetails().getAuthorizationUri(); String authority = interceptAuthorizationUri(authorizationUri); IClientSecret clientCredential = ClientCredentialFactory .createFromSecret(clientRegistration.getClientSecret()); try { return ConfidentialClientApplication.builder(clientRegistration.getClientId(), clientCredential) .authority(authority) .build(); } catch (MalformedURLException e) { LOGGER.error("Failed to create ConfidentialClientApplication", e); } return null; } private String interceptAuthorizationUri(String authorizationUri) { int count = 0; int slashNumber = 4; for (int i = 0; i < authorizationUri.length(); i++) { if (authorizationUri.charAt(i) == '/') { count++; } if (count == slashNumber) { return authorizationUri.substring(0, i + 1); } } return null; } private void replyForbiddenWithWwwAuthenticateHeader(String claims) { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletResponse response = attr.getResponse(); Assert.notNull(response, "HttpServletResponse should not be null."); response.setStatus(HttpStatus.FORBIDDEN.value()); Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put(Constants.CONDITIONAL_ACCESS_POLICY_CLAIMS, claims); parameters.put(OAuth2ParameterNames.ERROR, OAuth2ErrorCodes.INVALID_TOKEN); parameters.put(OAuth2ParameterNames.ERROR_DESCRIPTION, "The resource server requires higher privileges " + "than " + "provided by the access token"); response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Constants.BEARER_PREFIX + parameters.toString()); } }
what if move "LOGGER.log(INFO, "Using managed identity with client ID: {0}", clientId);" here
private String getAccessTokenOnAppService(String resource, String clientId) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); if (clientId != null) { LOGGER.log(INFO, "Using managed identity with client ID: {0}", clientId); } String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); if (clientId != null) { url.append("&clientid=").append(clientId); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
url.append("&clientid=").append(clientId);
private String getAccessTokenOnAppService(String resource, String clientId) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); if (clientId != null) { url.append("&clientid=").append(clientId); LOGGER.log(INFO, "Using managed identity with client ID: {0}", clientId); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned) * @return the authorization token. */ public String getAccessToken(String resource, String identity) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource, identity); } else { result = getAccessTokenOnOthers(resource, identity); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String aadAuthenticationUrl, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[]{ resource, tenantId, clientId, clientSecret}); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(aadAuthenticationUrl == null ? OAUTH2_TOKEN_BASE_URL : aadAuthenticationUrl) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ private String getAccessTokenOnOthers(String resource, String identity) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); if (identity != null) { LOGGER.log(INFO, "Using managed identity with object ID: {0}", identity); } String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); if (identity != null) { url.append("&object_id=").append(identity); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned) * @return the authorization token. */ public String getAccessToken(String resource, String identity) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource, identity); } else { result = getAccessTokenOnOthers(resource, identity); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String aadAuthenticationUrl, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[]{ resource, tenantId, clientId, clientSecret}); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(aadAuthenticationUrl == null ? OAUTH2_TOKEN_BASE_URL : aadAuthenticationUrl) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @param clientId the user-assigned managed identity (null if system-assigned). * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ private String getAccessTokenOnOthers(String resource, String identity) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); if (identity != null) { LOGGER.log(INFO, "Using managed identity with object ID: {0}", identity); } String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); if (identity != null) { url.append("&object_id=").append(identity); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
Hi, what is your concern of it? I think it's helpful to inform users about the flow of acquiring tokens and also debug.
private String getAccessTokenOnAppService(String resource, String clientId) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); if (clientId != null) { LOGGER.log(INFO, "Using managed identity with client ID: {0}", clientId); } String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); if (clientId != null) { url.append("&clientid=").append(clientId); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
url.append("&clientid=").append(clientId);
private String getAccessTokenOnAppService(String resource, String clientId) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); if (clientId != null) { url.append("&clientid=").append(clientId); LOGGER.log(INFO, "Using managed identity with client ID: {0}", clientId); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned) * @return the authorization token. */ public String getAccessToken(String resource, String identity) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource, identity); } else { result = getAccessTokenOnOthers(resource, identity); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String aadAuthenticationUrl, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[]{ resource, tenantId, clientId, clientSecret}); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(aadAuthenticationUrl == null ? OAUTH2_TOKEN_BASE_URL : aadAuthenticationUrl) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ private String getAccessTokenOnOthers(String resource, String identity) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); if (identity != null) { LOGGER.log(INFO, "Using managed identity with object ID: {0}", identity); } String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); if (identity != null) { url.append("&object_id=").append(identity); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned) * @return the authorization token. */ public String getAccessToken(String resource, String identity) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource, identity); } else { result = getAccessTokenOnOthers(resource, identity); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String aadAuthenticationUrl, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[]{ resource, tenantId, clientId, clientSecret}); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(aadAuthenticationUrl == null ? OAUTH2_TOKEN_BASE_URL : aadAuthenticationUrl) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @param clientId the user-assigned managed identity (null if system-assigned). * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ private String getAccessTokenOnOthers(String resource, String identity) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); if (identity != null) { LOGGER.log(INFO, "Using managed identity with object ID: {0}", identity); } String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); if (identity != null) { url.append("&object_id=").append(identity); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
IMU, @backwind1233 's concern is that `if (clientId != null)` appeared more than one time.
private String getAccessTokenOnAppService(String resource, String clientId) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); if (clientId != null) { LOGGER.log(INFO, "Using managed identity with client ID: {0}", clientId); } String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); if (clientId != null) { url.append("&clientid=").append(clientId); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
url.append("&clientid=").append(clientId);
private String getAccessTokenOnAppService(String resource, String clientId) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); if (clientId != null) { url.append("&clientid=").append(clientId); LOGGER.log(INFO, "Using managed identity with client ID: {0}", clientId); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned) * @return the authorization token. */ public String getAccessToken(String resource, String identity) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource, identity); } else { result = getAccessTokenOnOthers(resource, identity); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String aadAuthenticationUrl, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[]{ resource, tenantId, clientId, clientSecret}); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(aadAuthenticationUrl == null ? OAUTH2_TOKEN_BASE_URL : aadAuthenticationUrl) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ private String getAccessTokenOnOthers(String resource, String identity) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); if (identity != null) { LOGGER.log(INFO, "Using managed identity with object ID: {0}", identity); } String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); if (identity != null) { url.append("&object_id=").append(identity); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned) * @return the authorization token. */ public String getAccessToken(String resource, String identity) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource, identity); } else { result = getAccessTokenOnOthers(resource, identity); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String aadAuthenticationUrl, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[]{ resource, tenantId, clientId, clientSecret}); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(aadAuthenticationUrl == null ? OAUTH2_TOKEN_BASE_URL : aadAuthenticationUrl) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @param clientId the user-assigned managed identity (null if system-assigned). * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ private String getAccessTokenOnOthers(String resource, String identity) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); if (identity != null) { LOGGER.log(INFO, "Using managed identity with object ID: {0}", identity); } String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); if (identity != null) { url.append("&object_id=").append(identity); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
@chenrujun yes @yiliuTo ![image](https://user-images.githubusercontent.com/4465723/113372867-2d5a3580-939c-11eb-8e62-f5f35011b7a5.png)
private String getAccessTokenOnAppService(String resource, String clientId) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); if (clientId != null) { LOGGER.log(INFO, "Using managed identity with client ID: {0}", clientId); } String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); if (clientId != null) { url.append("&clientid=").append(clientId); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
url.append("&clientid=").append(clientId);
private String getAccessTokenOnAppService(String resource, String clientId) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); if (clientId != null) { url.append("&clientid=").append(clientId); LOGGER.log(INFO, "Using managed identity with client ID: {0}", clientId); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned) * @return the authorization token. */ public String getAccessToken(String resource, String identity) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource, identity); } else { result = getAccessTokenOnOthers(resource, identity); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String aadAuthenticationUrl, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[]{ resource, tenantId, clientId, clientSecret}); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(aadAuthenticationUrl == null ? OAUTH2_TOKEN_BASE_URL : aadAuthenticationUrl) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ private String getAccessTokenOnOthers(String resource, String identity) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); if (identity != null) { LOGGER.log(INFO, "Using managed identity with object ID: {0}", identity); } String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); if (identity != null) { url.append("&object_id=").append(identity); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned) * @return the authorization token. */ public String getAccessToken(String resource, String identity) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource, identity); } else { result = getAccessTokenOnOthers(resource, identity); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String aadAuthenticationUrl, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[]{ resource, tenantId, clientId, clientSecret}); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(aadAuthenticationUrl == null ? OAUTH2_TOKEN_BASE_URL : aadAuthenticationUrl) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @param clientId the user-assigned managed identity (null if system-assigned). * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @param identity the user-assigned identity (null if system-assigned). * @return the authorization token. */ private String getAccessTokenOnOthers(String resource, String identity) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); if (identity != null) { LOGGER.log(INFO, "Using managed identity with object ID: {0}", identity); } String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); if (identity != null) { url.append("&object_id=").append(identity); } HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccessToken(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
This should be handled in a deterministic manner.
void createNewLink() { ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(1); StepVerifier.create(processor) .then(() -> { messagePublisher.next(message1, message2); }) .expectNext(message1) .expectNext(message2) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); processor.dispose(); verify(link1, atMost(3)).addCredits(eq(PREFETCH - 1)); verify(link1, atLeast(2)).addCredits(eq(PREFETCH - 1)); }
void createNewLink() throws InterruptedException { final CountDownLatch countDownLatch = new CountDownLatch(2); ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(1); doAnswer((invocation) -> { countDownLatch.countDown(); return null; }).when(link1).addCredits(eq(PREFETCH - 1)); StepVerifier.create(processor) .then(() -> { messagePublisher.next(message1, message2); }) .expectNext(message1) .expectNext(message2) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); processor.dispose(); final boolean awaited = countDownLatch.await(5, TimeUnit.SECONDS); Assertions.assertTrue(awaited); }
class ServiceBusReceiveLinkProcessorTest { private static final int PREFETCH = 5; @Mock private ServiceBusReceiveLink link1; @Mock private ServiceBusReceiveLink link2; @Mock private ServiceBusReceiveLink link3; @Mock private AmqpRetryPolicy retryPolicy; @Mock private Message message1; @Mock private Message message2; @Captor private ArgumentCaptor<Supplier<Integer>> creditSupplierCaptor; private final TestPublisher<AmqpEndpointState> endpointProcessor = TestPublisher.create(); private final TestPublisher<Message> messagePublisher = TestPublisher.create(); private ServiceBusReceiveLinkProcessor linkProcessor; private ServiceBusReceiveLinkProcessor linkProcessorNoPrefetch; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(10)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @BeforeEach void setup() { MockitoAnnotations.initMocks(this); linkProcessor = new ServiceBusReceiveLinkProcessor(PREFETCH, retryPolicy); linkProcessorNoPrefetch = new ServiceBusReceiveLinkProcessor(0, retryPolicy); when(link1.getEndpointStates()).thenReturn(endpointProcessor.flux()); when(link1.receive()).thenReturn(messagePublisher.flux()); } @AfterEach void teardown() { Mockito.framework().clearInlineMocks(); } @Test void constructor() { assertThrows(NullPointerException.class, () -> new ServiceBusReceiveLinkProcessor(PREFETCH, null)); assertThrows(IllegalArgumentException.class, () -> new ServiceBusReceiveLinkProcessor(-1, retryPolicy)); } /** * Verifies that we can get a new AMQP receive link and fetch a few messages. */ @Test /** * Verifies that we respect the back pressure request when it is in range 1 - 100. */ @Test void respectsBackpressureInRange() { final int backpressure = 15; ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessorNoPrefetch); StepVerifier.create(processor, backpressure) .then(() -> messagePublisher.next(message1)) .expectNext(message1) .thenCancel() .verify(); verify(link1).addCredits(backpressure); } /** * Verifies we don't set the back pressure when it is too low. */ @Test void respectsBackpressureLessThanMinimum() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final int backpressure = -1; ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(1); semaphore.acquire(); processor.subscribe( e -> System.out.println("message: " + e), Assertions::fail, () -> System.out.println("Complete."), s -> { s.request(backpressure); semaphore.release(); }); assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS)); verify(link1, never()).addCredits(anyInt()); verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture()); Supplier<Integer> value = creditSupplierCaptor.getValue(); assertNotNull(value); final Integer creditValue = value.get(); assertEquals(0, creditValue); } /** * Verifies that we can only subscribe once. */ @Test void onSubscribingTwiceThrowsException() { ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); processor.subscribe(); StepVerifier.create(processor) .expectError(IllegalStateException.class) .verify(); } /** * Verifies that we can get subsequent AMQP links when the first one is closed. */ @Test void newLinkOnClose() { final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3}; final Message message3 = mock(Message.class); final Message message4 = mock(Message.class); final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor); final TestPublisher<AmqpEndpointState> connection2EndpointProcessor = TestPublisher.create(); when(link2.getEndpointStates()).thenReturn(connection2EndpointProcessor.flux()); when(link2.receive()).thenReturn(Flux.create(sink -> sink.next(message2))); when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link3.receive()).thenReturn(Flux.create(sink -> { sink.next(message3); sink.next(message4); })); when(link1.getCredits()).thenReturn(1); when(link2.getCredits()).thenReturn(1); when(link3.getCredits()).thenReturn(1); StepVerifier.create(processor) .then(() -> messagePublisher.next(message1)) .expectNext(message1) .then(() -> { endpointProcessor.complete(); }) .expectNext(message2) .then(() -> { connection2EndpointProcessor.complete(); }) .expectNext(message3) .expectNext(message4) .then(() -> { processor.cancel(); }) .verifyComplete(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); } /** * Verifies that we can get the next AMQP link when the first one encounters a retryable error. */ @Disabled("Fails on Ubuntu 18") @Test void newLinkOnRetryableError() { final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2}; final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor); when(link2.getEndpointStates()).thenReturn(Flux.defer(() -> Flux.create(e -> { e.next(AmqpEndpointState.ACTIVE); }))); when(link2.receive()).thenReturn(Flux.just(message2)); final AmqpException amqpException = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error", new AmqpErrorContext("test-namespace")); when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(Duration.ofSeconds(1)); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); messagePublisher.next(message1); }) .expectNext(message1) .then(() -> { endpointProcessor.error(amqpException); }) .expectNext(message2) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); } /** * Verifies that an error is propagated when the first connection encounters a non-retryable error. */ @Test void nonRetryableError() { final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2}; TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.createCold(); endpointStates.next(AmqpEndpointState.ACTIVE); final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor); final Message message3 = mock(Message.class); when(link2.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link2.receive()).thenReturn(Flux.just(message2, message3)); final AmqpException amqpException = new AmqpException(false, AmqpErrorCondition.ARGUMENT_ERROR, "Non-retryable-error", new AmqpErrorContext("test-namespace")); when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(null); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); System.out.println("Emitting first message."); messagePublisher.next(message1); }) .assertNext(message -> { System.out.println("Asserting first message."); assertSame(message1, message); }) .then(() -> { System.out.println("Outputting exception."); endpointProcessor.error(amqpException); }) .expectErrorSatisfies(error -> { System.out.println("Asserting exception."); assertTrue(error instanceof AmqpException); AmqpException exception = (AmqpException) error; assertFalse(exception.isTransient()); assertEquals(amqpException.getErrorCondition(), exception.getErrorCondition()); assertEquals(amqpException.getMessage(), exception.getMessage()); }) .verify(); assertTrue(processor.isTerminated()); assertTrue(processor.hasError()); assertSame(amqpException, processor.getError()); } /** * Verifies that when there are no subscribers, one request is fetched up stream. */ @Test void noSubscribers() { final Subscription subscription = mock(Subscription.class); linkProcessor.onSubscribe(subscription); verify(subscription).request(eq(1L)); } /** * Verifies that when the instance is terminated, no request is fetched from upstream. */ @Test void noSubscribersWhenTerminated() { final Subscription subscription = mock(Subscription.class); linkProcessor.cancel(); linkProcessor.onSubscribe(subscription); verifyNoInteractions(subscription); } /** * Verifies it keeps trying to get a link and stops after retries are exhausted. */ @Disabled("Fails on Ubuntu 18") @Test void retriesUntilExhausted() { final Duration delay = Duration.ofSeconds(1); final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3}; final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor); final DirectProcessor<AmqpEndpointState> link2StateProcessor = DirectProcessor.create(); final FluxSink<AmqpEndpointState> link2StateSink = link2StateProcessor.sink(); when(link2.getEndpointStates()).thenReturn(link2StateProcessor); when(link2.receive()).thenReturn(Flux.never()); when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link3.receive()).thenReturn(Flux.never()); final AmqpException amqpException = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error", new AmqpErrorContext("test-namespace")); final AmqpException amqpException2 = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error", new AmqpErrorContext("test-namespace")); when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(delay); when(retryPolicy.calculateRetryDelay(amqpException2, 2)).thenReturn(null); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); messagePublisher.next(message1); }) .expectNext(message1) .then(() -> endpointProcessor.error(amqpException)) .thenAwait(delay) .then(() -> link2StateSink.error(amqpException2)) .expectErrorSatisfies(error -> assertSame(amqpException2, error)) .verify(); assertTrue(processor.isTerminated()); assertTrue(processor.hasError()); assertSame(amqpException2, processor.getError()); } /** * Does not request another link when upstream is closed. */ @Test void doNotRetryWhenParentConnectionIsClosed() { final TestPublisher<ServiceBusReceiveLink> linkGenerator = TestPublisher.create(); final ServiceBusReceiveLinkProcessor processor = linkGenerator.flux().subscribeWith(linkProcessor); final TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.create(); final TestPublisher<Message> messages = TestPublisher.create(); when(link1.getEndpointStates()).thenReturn(endpointStates.flux()); when(link1.receive()).thenReturn(messages.flux()); final TestPublisher<AmqpEndpointState> endpointStates2 = TestPublisher.create(); when(link2.getEndpointStates()).thenReturn(endpointStates2.flux()); when(link2.receive()).thenReturn(Flux.never()); StepVerifier.create(processor) .then(() -> { linkGenerator.next(link1); endpointStates.next(AmqpEndpointState.ACTIVE); messages.next(message1); }) .expectNext(message1) .then(linkGenerator::complete) .then(endpointStates::complete) .expectComplete() .verify(); assertTrue(processor.isTerminated()); } @Test void requiresNonNull() { assertThrows(NullPointerException.class, () -> linkProcessor.onNext(null)); assertThrows(NullPointerException.class, () -> linkProcessor.onError(null)); } /** * Verifies that we respect the back pressure request and stop emitting. */ @Test void stopsEmittingAfterBackPressure() { final int backpressure = 5; ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(0, 5, 4, 3, 2, 1); StepVerifier.create(processor, backpressure) .then(() -> { for (int i = 0; i < backpressure + 2; i++) { messagePublisher.next(message2); } }) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(2)) .thenCancel() .verify(); } @Test void receivesUntilFirstLinkClosed() { ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(0); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); messagePublisher.next(message1, message2); }) .expectNext(message1) .expectNext(message2) .then(() -> endpointProcessor.complete()) .expectComplete() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); verify(link1, times(3)).addCredits(eq(PREFETCH)); verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture()); Supplier<Integer> value = creditSupplierCaptor.getValue(); assertNotNull(value); final Integer creditValue = value.get(); assertEquals(0, creditValue); } @Test void receivesFromFirstLink() { ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(0); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); messagePublisher.next(message1, message2); }) .expectNext(message1) .expectNext(message2) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); processor.dispose(); verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture()); Supplier<Integer> value = creditSupplierCaptor.getValue(); assertNotNull(value); final Integer creditValue = value.get(); assertEquals(0, creditValue); verify(link1, atMost(3)).addCredits(eq(PREFETCH)); verify(link1, atLeast(2)).addCredits(eq(PREFETCH)); } /** * Verifies that when we request back pressure amounts, if it only requests a certain number of events, only that * number is consumed. */ @Test void backpressureRequestOnlyEmitsThatAmount() { final int backpressure = PREFETCH; final int existingCredits = 1; final int expectedCredits = backpressure - existingCredits; ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(existingCredits); StepVerifier.create(processor, backpressure) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); final int emitted = backpressure + 5; for (int i = 0; i < emitted; i++) { Message message = mock(Message.class); messagePublisher.next(message); } }) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); verify(link1, times(backpressure + 1)).addCredits(expectedCredits); verify(link1).setEmptyCreditListener(any()); } private static Flux<ServiceBusReceiveLink> createSink(ServiceBusReceiveLink[] links) { return Flux.create(emitter -> { final AtomicInteger counter = new AtomicInteger(); emitter.onRequest(request -> { for (int i = 0; i < request; i++) { final int index = counter.getAndIncrement(); if (index == links.length) { emitter.error(new RuntimeException(String.format( "Cannot emit more. Index: %s. index, links.length))); break; } emitter.next(links[index]); } }); }, FluxSink.OverflowStrategy.BUFFER); } @Test void updateDispositionDoesNotAddCredit() { ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); final String lockToken = "lockToken"; final DeliveryState deliveryState = mock(DeliveryState.class); when(link1.getCredits()).thenReturn(0); when(link1.updateDisposition(eq(lockToken), eq(deliveryState))).thenReturn(Mono.empty()); StepVerifier.create(processor) .then(() -> processor.updateDisposition(lockToken, deliveryState)) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); verify(link1).addCredits(eq(PREFETCH)); verify(link1).updateDisposition(eq(lockToken), eq(deliveryState)); } }
class ServiceBusReceiveLinkProcessorTest { private static final int PREFETCH = 5; @Mock private ServiceBusReceiveLink link1; @Mock private ServiceBusReceiveLink link2; @Mock private ServiceBusReceiveLink link3; @Mock private AmqpRetryPolicy retryPolicy; @Mock private Message message1; @Mock private Message message2; @Captor private ArgumentCaptor<Supplier<Integer>> creditSupplierCaptor; private final TestPublisher<AmqpEndpointState> endpointProcessor = TestPublisher.create(); private final TestPublisher<Message> messagePublisher = TestPublisher.create(); private ServiceBusReceiveLinkProcessor linkProcessor; private ServiceBusReceiveLinkProcessor linkProcessorNoPrefetch; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(10)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @BeforeEach void setup() { MockitoAnnotations.initMocks(this); linkProcessor = new ServiceBusReceiveLinkProcessor(PREFETCH, retryPolicy); linkProcessorNoPrefetch = new ServiceBusReceiveLinkProcessor(0, retryPolicy); when(link1.getEndpointStates()).thenReturn(endpointProcessor.flux()); when(link1.receive()).thenReturn(messagePublisher.flux()); } @AfterEach void teardown() { Mockito.framework().clearInlineMocks(); } @Test void constructor() { assertThrows(NullPointerException.class, () -> new ServiceBusReceiveLinkProcessor(PREFETCH, null)); assertThrows(IllegalArgumentException.class, () -> new ServiceBusReceiveLinkProcessor(-1, retryPolicy)); } /** * Verifies that we can get a new AMQP receive link and fetch a few messages. */ @Test /** * Verifies that we respect the back pressure request when it is in range 1 - 100. */ @Test void respectsBackpressureInRange() { final int backpressure = 15; ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessorNoPrefetch); StepVerifier.create(processor, backpressure) .then(() -> messagePublisher.next(message1)) .expectNext(message1) .thenCancel() .verify(); verify(link1).addCredits(backpressure); } /** * Verifies we don't set the back pressure when it is too low. */ @Test void respectsBackpressureLessThanMinimum() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final int backpressure = -1; ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(1); semaphore.acquire(); processor.subscribe( e -> System.out.println("message: " + e), Assertions::fail, () -> System.out.println("Complete."), s -> { s.request(backpressure); semaphore.release(); }); assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS)); verify(link1, never()).addCredits(anyInt()); verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture()); Supplier<Integer> value = creditSupplierCaptor.getValue(); assertNotNull(value); final Integer creditValue = value.get(); assertEquals(0, creditValue); } /** * Verifies that we can only subscribe once. */ @Test void onSubscribingTwiceThrowsException() { ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); processor.subscribe(); StepVerifier.create(processor) .expectError(IllegalStateException.class) .verify(); } /** * Verifies that we can get subsequent AMQP links when the first one is closed. */ @Test void newLinkOnClose() { final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3}; final Message message3 = mock(Message.class); final Message message4 = mock(Message.class); final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor); final TestPublisher<AmqpEndpointState> connection2EndpointProcessor = TestPublisher.create(); when(link2.getEndpointStates()).thenReturn(connection2EndpointProcessor.flux()); when(link2.receive()).thenReturn(Flux.create(sink -> sink.next(message2))); when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link3.receive()).thenReturn(Flux.create(sink -> { sink.next(message3); sink.next(message4); })); when(link1.getCredits()).thenReturn(1); when(link2.getCredits()).thenReturn(1); when(link3.getCredits()).thenReturn(1); StepVerifier.create(processor) .then(() -> messagePublisher.next(message1)) .expectNext(message1) .then(() -> { endpointProcessor.complete(); }) .expectNext(message2) .then(() -> { connection2EndpointProcessor.complete(); }) .expectNext(message3) .expectNext(message4) .then(() -> { processor.cancel(); }) .verifyComplete(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); } /** * Verifies that we can get the next AMQP link when the first one encounters a retryable error. */ @Disabled("Fails on Ubuntu 18") @Test void newLinkOnRetryableError() { final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2}; final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor); when(link2.getEndpointStates()).thenReturn(Flux.defer(() -> Flux.create(e -> { e.next(AmqpEndpointState.ACTIVE); }))); when(link2.receive()).thenReturn(Flux.just(message2)); final AmqpException amqpException = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error", new AmqpErrorContext("test-namespace")); when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(Duration.ofSeconds(1)); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); messagePublisher.next(message1); }) .expectNext(message1) .then(() -> { endpointProcessor.error(amqpException); }) .expectNext(message2) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); } /** * Verifies that an error is propagated when the first connection encounters a non-retryable error. */ @Test void nonRetryableError() { final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2}; TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.createCold(); endpointStates.next(AmqpEndpointState.ACTIVE); final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor); final Message message3 = mock(Message.class); when(link2.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link2.receive()).thenReturn(Flux.just(message2, message3)); final AmqpException amqpException = new AmqpException(false, AmqpErrorCondition.ARGUMENT_ERROR, "Non-retryable-error", new AmqpErrorContext("test-namespace")); when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(null); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); System.out.println("Emitting first message."); messagePublisher.next(message1); }) .assertNext(message -> { System.out.println("Asserting first message."); assertSame(message1, message); }) .then(() -> { System.out.println("Outputting exception."); endpointProcessor.error(amqpException); }) .expectErrorSatisfies(error -> { System.out.println("Asserting exception."); assertTrue(error instanceof AmqpException); AmqpException exception = (AmqpException) error; assertFalse(exception.isTransient()); assertEquals(amqpException.getErrorCondition(), exception.getErrorCondition()); assertEquals(amqpException.getMessage(), exception.getMessage()); }) .verify(); assertTrue(processor.isTerminated()); assertTrue(processor.hasError()); assertSame(amqpException, processor.getError()); } /** * Verifies that when there are no subscribers, one request is fetched up stream. */ @Test void noSubscribers() { final Subscription subscription = mock(Subscription.class); linkProcessor.onSubscribe(subscription); verify(subscription).request(eq(1L)); } /** * Verifies that when the instance is terminated, no request is fetched from upstream. */ @Test void noSubscribersWhenTerminated() { final Subscription subscription = mock(Subscription.class); linkProcessor.cancel(); linkProcessor.onSubscribe(subscription); verifyNoInteractions(subscription); } /** * Verifies it keeps trying to get a link and stops after retries are exhausted. */ @Disabled("Fails on Ubuntu 18") @Test void retriesUntilExhausted() { final Duration delay = Duration.ofSeconds(1); final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3}; final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor); final DirectProcessor<AmqpEndpointState> link2StateProcessor = DirectProcessor.create(); final FluxSink<AmqpEndpointState> link2StateSink = link2StateProcessor.sink(); when(link2.getEndpointStates()).thenReturn(link2StateProcessor); when(link2.receive()).thenReturn(Flux.never()); when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link3.receive()).thenReturn(Flux.never()); final AmqpException amqpException = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error", new AmqpErrorContext("test-namespace")); final AmqpException amqpException2 = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error", new AmqpErrorContext("test-namespace")); when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(delay); when(retryPolicy.calculateRetryDelay(amqpException2, 2)).thenReturn(null); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); messagePublisher.next(message1); }) .expectNext(message1) .then(() -> endpointProcessor.error(amqpException)) .thenAwait(delay) .then(() -> link2StateSink.error(amqpException2)) .expectErrorSatisfies(error -> assertSame(amqpException2, error)) .verify(); assertTrue(processor.isTerminated()); assertTrue(processor.hasError()); assertSame(amqpException2, processor.getError()); } /** * Does not request another link when upstream is closed. */ @Test void doNotRetryWhenParentConnectionIsClosed() { final TestPublisher<ServiceBusReceiveLink> linkGenerator = TestPublisher.create(); final ServiceBusReceiveLinkProcessor processor = linkGenerator.flux().subscribeWith(linkProcessor); final TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.create(); final TestPublisher<Message> messages = TestPublisher.create(); when(link1.getEndpointStates()).thenReturn(endpointStates.flux()); when(link1.receive()).thenReturn(messages.flux()); final TestPublisher<AmqpEndpointState> endpointStates2 = TestPublisher.create(); when(link2.getEndpointStates()).thenReturn(endpointStates2.flux()); when(link2.receive()).thenReturn(Flux.never()); StepVerifier.create(processor) .then(() -> { linkGenerator.next(link1); endpointStates.next(AmqpEndpointState.ACTIVE); messages.next(message1); }) .expectNext(message1) .then(linkGenerator::complete) .then(endpointStates::complete) .expectComplete() .verify(); assertTrue(processor.isTerminated()); } @Test void requiresNonNull() { assertThrows(NullPointerException.class, () -> linkProcessor.onNext(null)); assertThrows(NullPointerException.class, () -> linkProcessor.onError(null)); } /** * Verifies that we respect the back pressure request and stop emitting. */ @Test void stopsEmittingAfterBackPressure() { final int backpressure = 5; ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(0, 5, 4, 3, 2, 1); StepVerifier.create(processor, backpressure) .then(() -> { for (int i = 0; i < backpressure + 2; i++) { messagePublisher.next(message2); } }) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(2)) .thenCancel() .verify(); } @Test void receivesUntilFirstLinkClosed() { ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(0); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); messagePublisher.next(message1, message2); }) .expectNext(message1) .expectNext(message2) .then(() -> endpointProcessor.complete()) .expectComplete() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); verify(link1, times(3)).addCredits(eq(PREFETCH)); verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture()); Supplier<Integer> value = creditSupplierCaptor.getValue(); assertNotNull(value); final Integer creditValue = value.get(); assertEquals(0, creditValue); } @Test void receivesFromFirstLink() throws InterruptedException { final CountDownLatch countDownLatch = new CountDownLatch(2); ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(0); doAnswer((i) -> { countDownLatch.countDown(); return null; }).when(link1).addCredits(eq(PREFETCH)); StepVerifier.create(processor) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); messagePublisher.next(message1, message2); }) .expectNext(message1) .expectNext(message2) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); processor.dispose(); verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture()); Supplier<Integer> value = creditSupplierCaptor.getValue(); assertNotNull(value); final Integer creditValue = value.get(); assertEquals(0, creditValue); final boolean awaited = countDownLatch.await(5, TimeUnit.SECONDS); Assertions.assertTrue(awaited); } /** * Verifies that when we request back pressure amounts, if it only requests a certain number of events, only that * number is consumed. */ @Test void backpressureRequestOnlyEmitsThatAmount() { final int backpressure = PREFETCH; final int existingCredits = 1; final int expectedCredits = backpressure - existingCredits; ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor); when(link1.getCredits()).thenReturn(existingCredits); StepVerifier.create(processor, backpressure) .then(() -> { endpointProcessor.next(AmqpEndpointState.ACTIVE); final int emitted = backpressure + 5; for (int i = 0; i < emitted; i++) { Message message = mock(Message.class); messagePublisher.next(message); } }) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); verify(link1, times(backpressure + 1)).addCredits(expectedCredits); verify(link1).setEmptyCreditListener(any()); } private static Flux<ServiceBusReceiveLink> createSink(ServiceBusReceiveLink[] links) { return Flux.create(emitter -> { final AtomicInteger counter = new AtomicInteger(); emitter.onRequest(request -> { for (int i = 0; i < request; i++) { final int index = counter.getAndIncrement(); if (index == links.length) { emitter.error(new RuntimeException(String.format( "Cannot emit more. Index: %s. index, links.length))); break; } emitter.next(links[index]); } }); }, FluxSink.OverflowStrategy.BUFFER); } @Test void updateDispositionDoesNotAddCredit() { ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1)) .subscribeWith(linkProcessor); final String lockToken = "lockToken"; final DeliveryState deliveryState = mock(DeliveryState.class); when(link1.getCredits()).thenReturn(0); when(link1.updateDisposition(eq(lockToken), eq(deliveryState))).thenReturn(Mono.empty()); StepVerifier.create(processor) .then(() -> processor.updateDisposition(lockToken, deliveryState)) .thenCancel() .verify(); assertTrue(processor.isTerminated()); assertFalse(processor.hasError()); assertNull(processor.getError()); verify(link1).addCredits(eq(PREFETCH)); verify(link1).updateDisposition(eq(lockToken), eq(deliveryState)); } }
SyncToken policy is only used internally, a user should not use the policy. It is safe to replace the SyncTokenPolicy by force. So we can control the policy.
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.add(syncTokenPolicy); policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); }
return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy);
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy(); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.add(syncTokenPolicy); policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy(); private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
Sync tokens won't be applied in this case as the policy isn't part of the pipeline. Should we pass null instead and throw `IllegalStateException` in the clients if it doesn't have a sync token policy?
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.add(syncTokenPolicy); policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); }
return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy);
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy(); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.add(syncTokenPolicy); policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy(); private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
Additionally, another options would be scanning through the policies in the pipeline in an attempt to find a `SyncTokenPolicy` and passing that to the service client. It still may end up being null, so adding the additional logic to throw if `SyncTokenPolicy` is null still would apply
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.add(syncTokenPolicy); policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); }
return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy);
public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ConfigurationServiceVersion serviceVersion = (version != null) ? version : ConfigurationServiceVersion.getLatest(); String buildEndpoint = endpoint; if (tokenCredential == null) { buildEndpoint = getBuildEndpoint(); } Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null."); SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy(); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy( getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); policies.add(ADD_HEADERS_POLICY); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add( new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint))); } else if (credential != null) { policies.add(new ConfigurationCredentialsPolicy(credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.add(syncTokenPolicy); policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach( header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline, serviceVersion, syncTokenPolicy); }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy(); private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String CLIENT_NAME; private static final String CLIENT_VERSION; private static final HttpPipelinePolicy ADD_HEADERS_POLICY; static { Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders() .put("x-ms-return-client-request-id", "true") .put("Content-Type", "application/json") .put("Accept", "application/vnd.microsoft.azconfig.kv+json")); } private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private ConfigurationClientCredentials credential; private TokenCredential tokenCredential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private Configuration configuration; private ConfigurationServiceVersion version; /** * Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link * ConfigurationAsyncClient ConfigurationAsyncClients}. */ public ConfigurationClientBuilder() { httpLogOptions = new HttpLogOptions(); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * <p> * If {@link * endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are * ignored. * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link * * * @throws IllegalStateException If {@link */ /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * * @param clientOptions {@link ClientOptions}. * * @return the updated ConfigurationClientBuilder object */ public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code connectionString} is null. * @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString} * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential TokenCredential used to authenticate HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is null. */ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies. * * @param policy The policy for service requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is null. */ public ConfigurationClientBuilder 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 HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used to retry requests. * <p> * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. * @return The updated ConfigurationClientBuilder object. * @deprecated Use {@link */ @Deprecated public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * A default retry policy will be used to build {@link ConfigurationAsyncClient} or * {@link ConfigurationClient} if this is not set. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ConfigurationServiceVersion} 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 ConfigurationServiceVersion} of the service to be used when making requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) { this.version = version; return this; } private String getBuildEndpoint() { if (endpoint != null) { return endpoint; } else if (credential != null) { return credential.getBaseUri(); } else { return null; } } }
Given the application continues to run when this happens we should downgrade the log level, I'm thinking info or verbose
public void updateSyncToken(String token) { final String[] syncTokens = token.split(COMMA); for (final String syncTokenString : syncTokens) { if (CoreUtils.isNullOrEmpty(syncTokenString)) { continue; } final SyncToken syncToken; try { syncToken = new SyncToken(syncTokenString); } catch (Exception ex){ logger.warning(SKIP_INVALID_TOKEN, syncTokenString); continue; } final String tokenId = syncToken.getId(); syncTokenMap.compute(tokenId, (key, existingSyncToken) -> { if (existingSyncToken == null || syncToken.getSequenceNumber() > existingSyncToken.getSequenceNumber()) { return syncToken; } return existingSyncToken; }); } }
logger.warning(SKIP_INVALID_TOKEN, syncTokenString);
public void updateSyncToken(String token) { final String[] syncTokens = token.split(COMMA); for (final String syncTokenString : syncTokens) { if (CoreUtils.isNullOrEmpty(syncTokenString)) { continue; } final SyncToken syncToken; try { syncToken = SyncToken.createSyncToken(syncTokenString); } catch (Exception ex) { logger.info(SKIP_INVALID_TOKEN, syncTokenString); continue; } final String tokenId = syncToken.getId(); syncTokenMap.compute(tokenId, (key, existingSyncToken) -> { if (existingSyncToken == null || syncToken.getSequenceNumber() > existingSyncToken.getSequenceNumber()) { return syncToken; } return existingSyncToken; }); } }
class SyncTokenPolicy implements HttpPipelinePolicy { private static final String COMMA = ","; private static final String EQUAL = "="; private static final String SYNC_TOKEN = "Sync-Token"; private final String SKIP_INVALID_TOKEN = "Skipping invalid sync token '{}'."; private final Map<String, SyncToken> syncTokenMap = new ConcurrentHashMap<>(); private final ClientLogger logger = new ClientLogger(SyncTokenPolicy.class); /** * Add or update the sync token to a thread safe map. * * @param context request context * @param next The next policy to invoke. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue != null) { updateSyncToken(syncTokenValue); } return Mono.just(httpResponse); }); } /** * Get all latest sync-tokens from the concurrent map and convert to one sync-token string. * All sync-tokens concatenated by a comma delimiter. * @return sync-token string */ private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); } /** * Update the existing synchronization tokens. * * @param token an external synchronization token to ensure service requests receive up-to-date values. */ }
class SyncTokenPolicy implements HttpPipelinePolicy { private static final String COMMA = ","; private static final String EQUAL = "="; private static final String SYNC_TOKEN = "Sync-Token"; private static final String SKIP_INVALID_TOKEN = "Skipping invalid sync token '{}'."; private final Map<String, SyncToken> syncTokenMap = new ConcurrentHashMap<>(); private final ClientLogger logger = new ClientLogger(SyncTokenPolicy.class); /** * Add or update the sync token to a thread safe map. * * @param context request context * @param next The next policy to invoke. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue != null) { updateSyncToken(syncTokenValue); } return Mono.just(httpResponse); }); } /** * Get all latest sync-tokens from the concurrent map and convert to one sync-token string. * All sync-tokens concatenated by a comma delimiter. * @return sync-token string */ private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); } /** * Update the existing synchronization tokens. * * @param token an external synchronization token to ensure service requests receive up-to-date values. */ }
Another option here, instead of throwing an exception in the constructor is using a factory pattern and returning null when `syncTokenString` isn't in the correct format. That way we don't have any overhead of stack traces when an illegal token is received
public void updateSyncToken(String token) { final String[] syncTokens = token.split(COMMA); for (final String syncTokenString : syncTokens) { if (CoreUtils.isNullOrEmpty(syncTokenString)) { continue; } final SyncToken syncToken; try { syncToken = new SyncToken(syncTokenString); } catch (Exception ex){ logger.warning(SKIP_INVALID_TOKEN, syncTokenString); continue; } final String tokenId = syncToken.getId(); syncTokenMap.compute(tokenId, (key, existingSyncToken) -> { if (existingSyncToken == null || syncToken.getSequenceNumber() > existingSyncToken.getSequenceNumber()) { return syncToken; } return existingSyncToken; }); } }
syncToken = new SyncToken(syncTokenString);
public void updateSyncToken(String token) { final String[] syncTokens = token.split(COMMA); for (final String syncTokenString : syncTokens) { if (CoreUtils.isNullOrEmpty(syncTokenString)) { continue; } final SyncToken syncToken; try { syncToken = SyncToken.createSyncToken(syncTokenString); } catch (Exception ex) { logger.info(SKIP_INVALID_TOKEN, syncTokenString); continue; } final String tokenId = syncToken.getId(); syncTokenMap.compute(tokenId, (key, existingSyncToken) -> { if (existingSyncToken == null || syncToken.getSequenceNumber() > existingSyncToken.getSequenceNumber()) { return syncToken; } return existingSyncToken; }); } }
class SyncTokenPolicy implements HttpPipelinePolicy { private static final String COMMA = ","; private static final String EQUAL = "="; private static final String SYNC_TOKEN = "Sync-Token"; private final String SKIP_INVALID_TOKEN = "Skipping invalid sync token '{}'."; private final Map<String, SyncToken> syncTokenMap = new ConcurrentHashMap<>(); private final ClientLogger logger = new ClientLogger(SyncTokenPolicy.class); /** * Add or update the sync token to a thread safe map. * * @param context request context * @param next The next policy to invoke. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue != null) { updateSyncToken(syncTokenValue); } return Mono.just(httpResponse); }); } /** * Get all latest sync-tokens from the concurrent map and convert to one sync-token string. * All sync-tokens concatenated by a comma delimiter. * @return sync-token string */ private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); } /** * Update the existing synchronization tokens. * * @param token an external synchronization token to ensure service requests receive up-to-date values. */ }
class SyncTokenPolicy implements HttpPipelinePolicy { private static final String COMMA = ","; private static final String EQUAL = "="; private static final String SYNC_TOKEN = "Sync-Token"; private static final String SKIP_INVALID_TOKEN = "Skipping invalid sync token '{}'."; private final Map<String, SyncToken> syncTokenMap = new ConcurrentHashMap<>(); private final ClientLogger logger = new ClientLogger(SyncTokenPolicy.class); /** * Add or update the sync token to a thread safe map. * * @param context request context * @param next The next policy to invoke. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue != null) { updateSyncToken(syncTokenValue); } return Mono.just(httpResponse); }); } /** * Get all latest sync-tokens from the concurrent map and convert to one sync-token string. * All sync-tokens concatenated by a comma delimiter. * @return sync-token string */ private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); } /** * Update the existing synchronization tokens. * * @param token an external synchronization token to ensure service requests receive up-to-date values. */ }
Any way we could cache this value until the map is mutated? Seems like this could result in a lot of duplicate string construction if the tokens aren't updated frequently. This doesn't need to be done eagerly if tokens update a lot
private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); }
return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue())
private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); }
class SyncTokenPolicy implements HttpPipelinePolicy { private static final String COMMA = ","; private static final String EQUAL = "="; private static final String SYNC_TOKEN = "Sync-Token"; private final String SKIP_INVALID_TOKEN = "Skipping invalid sync token '{}'."; private final Map<String, SyncToken> syncTokenMap = new ConcurrentHashMap<>(); private final ClientLogger logger = new ClientLogger(SyncTokenPolicy.class); /** * Add or update the sync token to a thread safe map. * * @param context request context * @param next The next policy to invoke. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue != null) { updateSyncToken(syncTokenValue); } return Mono.just(httpResponse); }); } /** * Get all latest sync-tokens from the concurrent map and convert to one sync-token string. * All sync-tokens concatenated by a comma delimiter. * @return sync-token string */ /** * Update the existing synchronization tokens. * * @param token an external synchronization token to ensure service requests receive up-to-date values. */ public void updateSyncToken(String token) { final String[] syncTokens = token.split(COMMA); for (final String syncTokenString : syncTokens) { if (CoreUtils.isNullOrEmpty(syncTokenString)) { continue; } final SyncToken syncToken; try { syncToken = new SyncToken(syncTokenString); } catch (Exception ex){ logger.warning(SKIP_INVALID_TOKEN, syncTokenString); continue; } final String tokenId = syncToken.getId(); syncTokenMap.compute(tokenId, (key, existingSyncToken) -> { if (existingSyncToken == null || syncToken.getSequenceNumber() > existingSyncToken.getSequenceNumber()) { return syncToken; } return existingSyncToken; }); } } }
class SyncTokenPolicy implements HttpPipelinePolicy { private static final String COMMA = ","; private static final String EQUAL = "="; private static final String SYNC_TOKEN = "Sync-Token"; private static final String SKIP_INVALID_TOKEN = "Skipping invalid sync token '{}'."; private final Map<String, SyncToken> syncTokenMap = new ConcurrentHashMap<>(); private final ClientLogger logger = new ClientLogger(SyncTokenPolicy.class); /** * Add or update the sync token to a thread safe map. * * @param context request context * @param next The next policy to invoke. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue != null) { updateSyncToken(syncTokenValue); } return Mono.just(httpResponse); }); } /** * Get all latest sync-tokens from the concurrent map and convert to one sync-token string. * All sync-tokens concatenated by a comma delimiter. * @return sync-token string */ /** * Update the existing synchronization tokens. * * @param token an external synchronization token to ensure service requests receive up-to-date values. */ public void updateSyncToken(String token) { final String[] syncTokens = token.split(COMMA); for (final String syncTokenString : syncTokens) { if (CoreUtils.isNullOrEmpty(syncTokenString)) { continue; } final SyncToken syncToken; try { syncToken = SyncToken.createSyncToken(syncTokenString); } catch (Exception ex) { logger.info(SKIP_INVALID_TOKEN, syncTokenString); continue; } final String tokenId = syncToken.getId(); syncTokenMap.compute(tokenId, (key, existingSyncToken) -> { if (existingSyncToken == null || syncToken.getSequenceNumber() > existingSyncToken.getSequenceNumber()) { return syncToken; } return existingSyncToken; }); } } }
https://github.com/Azure/azure-sdk-for-java/issues/20355 Created an issue to address this later since Monday is the code complete day.
private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); }
return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue())
private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); }
class SyncTokenPolicy implements HttpPipelinePolicy { private static final String COMMA = ","; private static final String EQUAL = "="; private static final String SYNC_TOKEN = "Sync-Token"; private final String SKIP_INVALID_TOKEN = "Skipping invalid sync token '{}'."; private final Map<String, SyncToken> syncTokenMap = new ConcurrentHashMap<>(); private final ClientLogger logger = new ClientLogger(SyncTokenPolicy.class); /** * Add or update the sync token to a thread safe map. * * @param context request context * @param next The next policy to invoke. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue != null) { updateSyncToken(syncTokenValue); } return Mono.just(httpResponse); }); } /** * Get all latest sync-tokens from the concurrent map and convert to one sync-token string. * All sync-tokens concatenated by a comma delimiter. * @return sync-token string */ /** * Update the existing synchronization tokens. * * @param token an external synchronization token to ensure service requests receive up-to-date values. */ public void updateSyncToken(String token) { final String[] syncTokens = token.split(COMMA); for (final String syncTokenString : syncTokens) { if (CoreUtils.isNullOrEmpty(syncTokenString)) { continue; } final SyncToken syncToken; try { syncToken = new SyncToken(syncTokenString); } catch (Exception ex){ logger.warning(SKIP_INVALID_TOKEN, syncTokenString); continue; } final String tokenId = syncToken.getId(); syncTokenMap.compute(tokenId, (key, existingSyncToken) -> { if (existingSyncToken == null || syncToken.getSequenceNumber() > existingSyncToken.getSequenceNumber()) { return syncToken; } return existingSyncToken; }); } } }
class SyncTokenPolicy implements HttpPipelinePolicy { private static final String COMMA = ","; private static final String EQUAL = "="; private static final String SYNC_TOKEN = "Sync-Token"; private static final String SKIP_INVALID_TOKEN = "Skipping invalid sync token '{}'."; private final Map<String, SyncToken> syncTokenMap = new ConcurrentHashMap<>(); private final ClientLogger logger = new ClientLogger(SyncTokenPolicy.class); /** * Add or update the sync token to a thread safe map. * * @param context request context * @param next The next policy to invoke. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue != null) { updateSyncToken(syncTokenValue); } return Mono.just(httpResponse); }); } /** * Get all latest sync-tokens from the concurrent map and convert to one sync-token string. * All sync-tokens concatenated by a comma delimiter. * @return sync-token string */ /** * Update the existing synchronization tokens. * * @param token an external synchronization token to ensure service requests receive up-to-date values. */ public void updateSyncToken(String token) { final String[] syncTokens = token.split(COMMA); for (final String syncTokenString : syncTokens) { if (CoreUtils.isNullOrEmpty(syncTokenString)) { continue; } final SyncToken syncToken; try { syncToken = SyncToken.createSyncToken(syncTokenString); } catch (Exception ex) { logger.info(SKIP_INVALID_TOKEN, syncTokenString); continue; } final String tokenId = syncToken.getId(); syncTokenMap.compute(tokenId, (key, existingSyncToken) -> { if (existingSyncToken == null || syncToken.getSequenceNumber() > existingSyncToken.getSequenceNumber()) { return syncToken; } return existingSyncToken; }); } } }
Remove all System.out.print* statements.
void receiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) throws InterruptedException { final int lockTimeoutDurationSeconds = 15; final int entityIndex = TestUtils.USE_CASE_PROCESSOR_RECEIVE; final Duration expectedMaxAutoLockRenew = Duration.ofSeconds(lockTimeoutDurationSeconds); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled).setMessageId(messageId); CountDownLatch countDownLatch = new CountDownLatch(2); setSender(entityType, entityIndex, isSessionEnabled); sendMessage(message).block(TIMEOUT); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); AmqpRetryOptions amqpRetryOptions = new AmqpRetryOptions().setTryTimeout(Duration.ofSeconds(lockTimeoutDurationSeconds)); processor = getSessionProcessorBuilder(false, entityType, entityIndex, false, amqpRetryOptions) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } else { this.processor = getProcessorBuilder(false, entityType, entityIndex, false) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } System.out.println("Starting the processor"); processor.start(); System.out.println("Listening for messages .. "); if (countDownLatch.await(lockTimeoutDurationSeconds * 4, TimeUnit.SECONDS)) { System.out.println("Message lock has been renewed. Now closing processor"); } else { System.out.println("Message not arrived, closing processor."); Assertions.fail("Message not arrived, closing processor."); } processor.close(); }
System.out.println("Starting the processor");
void receiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) throws InterruptedException { final int lockTimeoutDurationSeconds = 15; final int entityIndex = TestUtils.USE_CASE_PROCESSOR_RECEIVE; final Duration expectedMaxAutoLockRenew = Duration.ofSeconds(35); final String messageId = UUID.randomUUID().toString(); final AtomicReference<OffsetTime> lastMessageReceivedTime = new AtomicReference<>(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled).setMessageId(messageId); CountDownLatch countDownLatch = new CountDownLatch(2); setSender(entityType, entityIndex, isSessionEnabled); sendMessage(message).block(TIMEOUT); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); AmqpRetryOptions amqpRetryOptions = new AmqpRetryOptions() .setTryTimeout(Duration.ofSeconds(2 * lockTimeoutDurationSeconds)); processor = getSessionProcessorBuilder(false, entityType, entityIndex, false, amqpRetryOptions) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } else { this.processor = getProcessorBuilder(false, entityType, entityIndex, false) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } processor.start(); if (countDownLatch.await(lockTimeoutDurationSeconds * 6, TimeUnit.SECONDS)) { logger.info("Message lock has been renewed. Now closing processor"); } else { Assertions.fail("Message not arrived, closing processor."); } processor.close(); }
class ServiceBusProcessorClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final Scheduler scheduler = Schedulers.parallel(); private ServiceBusProcessorClient processor; private ServiceBusSenderAsyncClient sender; @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(processor, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } ServiceBusProcessorClientIntegrationTest() { super(new ClientLogger(ServiceBusProcessorClientIntegrationTest.class)); } /** * Validate that processor receive the message and {@code MaxAutoLockRenewDuration} is set on the * {@link ServiceBusReceiverAsyncClient}. The message lock is released by the client and same message received * again. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest private void processMessage(ServiceBusReceivedMessageContext context, CountDownLatch countDownLatch, String expectedMessageId) { ServiceBusReceivedMessage message = context.getMessage(); if (message.getMessageId().equals(expectedMessageId)) { System.out.printf("Processing message. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); countDownLatch.countDown(); } else { System.out.printf("Received message, message id did not match. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); } } private static void processError(ServiceBusErrorContext context, CountDownLatch countdownLatch) { System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'%n", context.getFullyQualifiedNamespace(), context.getEntityPath()); } protected ServiceBusClientBuilder.ServiceBusProcessorClientBuilder getProcessorBuilder(boolean useCredentials, MessagingEntityType entityType, int entityIndex, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(useCredentials, sharedConnection); switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.processor().queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder.processor().topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusClientBuilder.ServiceBusSessionProcessorClientBuilder getSessionProcessorBuilder(boolean useCredentials, MessagingEntityType entityType, int entityIndex, boolean sharedConnection, AmqpRetryOptions amqpRetryOptions) { ServiceBusClientBuilder builder = getBuilder(useCredentials, sharedConnection); builder.retryOptions(amqpRetryOptions); switch (entityType) { case QUEUE: final String queueName = getSessionQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder .sessionProcessor() .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSessionSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder.sessionProcessor() .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } private void setSender(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); } private ServiceBusClientBuilder getBuilder(boolean useCredentials, boolean sharedConnection) { return new ServiceBusClientBuilder() .connectionString(getConnectionString()) .proxyOptions(ProxyOptions.SYSTEM_DEFAULTS) .retryOptions(RETRY_OPTIONS) .transportType(AmqpTransportType.AMQP) .scheduler(scheduler); } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } }
class ServiceBusProcessorClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final Scheduler scheduler = Schedulers.parallel(); private ServiceBusProcessorClient processor; private ServiceBusSenderAsyncClient sender; @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(processor, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } ServiceBusProcessorClientIntegrationTest() { super(new ClientLogger(ServiceBusProcessorClientIntegrationTest.class)); } /** * Validate that processor receive the message and {@code MaxAutoLockRenewDuration} is set on the * {@link ServiceBusReceiverAsyncClient}. The message lock is released by the client and same message received * again. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest private void processMessage(ServiceBusReceivedMessageContext context, CountDownLatch countDownLatch, String expectedMessageId, AtomicReference<OffsetTime> lastMessageReceivedTime, int lockTimeoutDurationSeconds) { ServiceBusReceivedMessage message = context.getMessage(); if (message.getMessageId().equals(expectedMessageId)) { logger.info("Processing message. Session: {}, Sequence message.getSequenceNumber(), message.getBody()); if (lastMessageReceivedTime.get() == null) { lastMessageReceivedTime.set(OffsetTime.now()); countDownLatch.countDown(); } else { long messageReceivedAfterSeconds = Duration.between(lastMessageReceivedTime.get(), OffsetTime.now()).getSeconds(); logger.info("Processing message again. Session: {}, Sequence message.getSequenceNumber(), message.getBody(), messageReceivedAfterSeconds); if (messageReceivedAfterSeconds >= 2 * lockTimeoutDurationSeconds) { countDownLatch.countDown(); } } } else { logger.info("Received message, message id did not match. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); } } private void processError(ServiceBusErrorContext context, CountDownLatch countdownLatch) { logger.info("Error when receiving messages from namespace: {}. Entity: {}}", context.getFullyQualifiedNamespace(), context.getEntityPath()); }
Some output help to debug if any issue. I have changed them to use logger.
void receiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) throws InterruptedException { final int lockTimeoutDurationSeconds = 15; final int entityIndex = TestUtils.USE_CASE_PROCESSOR_RECEIVE; final Duration expectedMaxAutoLockRenew = Duration.ofSeconds(lockTimeoutDurationSeconds); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled).setMessageId(messageId); CountDownLatch countDownLatch = new CountDownLatch(2); setSender(entityType, entityIndex, isSessionEnabled); sendMessage(message).block(TIMEOUT); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); AmqpRetryOptions amqpRetryOptions = new AmqpRetryOptions().setTryTimeout(Duration.ofSeconds(lockTimeoutDurationSeconds)); processor = getSessionProcessorBuilder(false, entityType, entityIndex, false, amqpRetryOptions) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } else { this.processor = getProcessorBuilder(false, entityType, entityIndex, false) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } System.out.println("Starting the processor"); processor.start(); System.out.println("Listening for messages .. "); if (countDownLatch.await(lockTimeoutDurationSeconds * 4, TimeUnit.SECONDS)) { System.out.println("Message lock has been renewed. Now closing processor"); } else { System.out.println("Message not arrived, closing processor."); Assertions.fail("Message not arrived, closing processor."); } processor.close(); }
System.out.println("Starting the processor");
void receiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) throws InterruptedException { final int lockTimeoutDurationSeconds = 15; final int entityIndex = TestUtils.USE_CASE_PROCESSOR_RECEIVE; final Duration expectedMaxAutoLockRenew = Duration.ofSeconds(35); final String messageId = UUID.randomUUID().toString(); final AtomicReference<OffsetTime> lastMessageReceivedTime = new AtomicReference<>(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled).setMessageId(messageId); CountDownLatch countDownLatch = new CountDownLatch(2); setSender(entityType, entityIndex, isSessionEnabled); sendMessage(message).block(TIMEOUT); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); AmqpRetryOptions amqpRetryOptions = new AmqpRetryOptions() .setTryTimeout(Duration.ofSeconds(2 * lockTimeoutDurationSeconds)); processor = getSessionProcessorBuilder(false, entityType, entityIndex, false, amqpRetryOptions) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } else { this.processor = getProcessorBuilder(false, entityType, entityIndex, false) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } processor.start(); if (countDownLatch.await(lockTimeoutDurationSeconds * 6, TimeUnit.SECONDS)) { logger.info("Message lock has been renewed. Now closing processor"); } else { Assertions.fail("Message not arrived, closing processor."); } processor.close(); }
class ServiceBusProcessorClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final Scheduler scheduler = Schedulers.parallel(); private ServiceBusProcessorClient processor; private ServiceBusSenderAsyncClient sender; @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(processor, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } ServiceBusProcessorClientIntegrationTest() { super(new ClientLogger(ServiceBusProcessorClientIntegrationTest.class)); } /** * Validate that processor receive the message and {@code MaxAutoLockRenewDuration} is set on the * {@link ServiceBusReceiverAsyncClient}. The message lock is released by the client and same message received * again. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest private void processMessage(ServiceBusReceivedMessageContext context, CountDownLatch countDownLatch, String expectedMessageId) { ServiceBusReceivedMessage message = context.getMessage(); if (message.getMessageId().equals(expectedMessageId)) { System.out.printf("Processing message. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); countDownLatch.countDown(); } else { System.out.printf("Received message, message id did not match. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); } } private static void processError(ServiceBusErrorContext context, CountDownLatch countdownLatch) { System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'%n", context.getFullyQualifiedNamespace(), context.getEntityPath()); } protected ServiceBusClientBuilder.ServiceBusProcessorClientBuilder getProcessorBuilder(boolean useCredentials, MessagingEntityType entityType, int entityIndex, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(useCredentials, sharedConnection); switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.processor().queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder.processor().topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusClientBuilder.ServiceBusSessionProcessorClientBuilder getSessionProcessorBuilder(boolean useCredentials, MessagingEntityType entityType, int entityIndex, boolean sharedConnection, AmqpRetryOptions amqpRetryOptions) { ServiceBusClientBuilder builder = getBuilder(useCredentials, sharedConnection); builder.retryOptions(amqpRetryOptions); switch (entityType) { case QUEUE: final String queueName = getSessionQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder .sessionProcessor() .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSessionSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder.sessionProcessor() .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } private void setSender(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); } private ServiceBusClientBuilder getBuilder(boolean useCredentials, boolean sharedConnection) { return new ServiceBusClientBuilder() .connectionString(getConnectionString()) .proxyOptions(ProxyOptions.SYSTEM_DEFAULTS) .retryOptions(RETRY_OPTIONS) .transportType(AmqpTransportType.AMQP) .scheduler(scheduler); } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } }
class ServiceBusProcessorClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final Scheduler scheduler = Schedulers.parallel(); private ServiceBusProcessorClient processor; private ServiceBusSenderAsyncClient sender; @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(processor, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } ServiceBusProcessorClientIntegrationTest() { super(new ClientLogger(ServiceBusProcessorClientIntegrationTest.class)); } /** * Validate that processor receive the message and {@code MaxAutoLockRenewDuration} is set on the * {@link ServiceBusReceiverAsyncClient}. The message lock is released by the client and same message received * again. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest private void processMessage(ServiceBusReceivedMessageContext context, CountDownLatch countDownLatch, String expectedMessageId, AtomicReference<OffsetTime> lastMessageReceivedTime, int lockTimeoutDurationSeconds) { ServiceBusReceivedMessage message = context.getMessage(); if (message.getMessageId().equals(expectedMessageId)) { logger.info("Processing message. Session: {}, Sequence message.getSequenceNumber(), message.getBody()); if (lastMessageReceivedTime.get() == null) { lastMessageReceivedTime.set(OffsetTime.now()); countDownLatch.countDown(); } else { long messageReceivedAfterSeconds = Duration.between(lastMessageReceivedTime.get(), OffsetTime.now()).getSeconds(); logger.info("Processing message again. Session: {}, Sequence message.getSequenceNumber(), message.getBody(), messageReceivedAfterSeconds); if (messageReceivedAfterSeconds >= 2 * lockTimeoutDurationSeconds) { countDownLatch.countDown(); } } } else { logger.info("Received message, message id did not match. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); } } private void processError(ServiceBusErrorContext context, CountDownLatch countdownLatch) { logger.info("Error when receiving messages from namespace: {}. Entity: {}}", context.getFullyQualifiedNamespace(), context.getEntityPath()); }
This is set as the tryTimeoutDuration. Why do we need to configure this?
void receiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) throws InterruptedException { final int lockTimeoutDurationSeconds = 15; final int entityIndex = TestUtils.USE_CASE_PROCESSOR_RECEIVE; final Duration expectedMaxAutoLockRenew = Duration.ofSeconds(35); final String messageId = UUID.randomUUID().toString(); final AtomicReference<OffsetTime> lastMessageReceivedTime = new AtomicReference<>(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled).setMessageId(messageId); CountDownLatch countDownLatch = new CountDownLatch(2); setSender(entityType, entityIndex, isSessionEnabled); sendMessage(message).block(TIMEOUT); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); AmqpRetryOptions amqpRetryOptions = new AmqpRetryOptions() .setTryTimeout(Duration.ofSeconds(2 * lockTimeoutDurationSeconds)); processor = getSessionProcessorBuilder(false, entityType, entityIndex, false, amqpRetryOptions) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } else { this.processor = getProcessorBuilder(false, entityType, entityIndex, false) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } processor.start(); if (countDownLatch.await(lockTimeoutDurationSeconds * 6, TimeUnit.SECONDS)) { logger.info("Message lock has been renewed. Now closing processor"); } else { Assertions.fail("Message not arrived, closing processor."); } processor.close(); }
final int lockTimeoutDurationSeconds = 15;
void receiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) throws InterruptedException { final int lockTimeoutDurationSeconds = 15; final int entityIndex = TestUtils.USE_CASE_PROCESSOR_RECEIVE; final Duration expectedMaxAutoLockRenew = Duration.ofSeconds(35); final String messageId = UUID.randomUUID().toString(); final AtomicReference<OffsetTime> lastMessageReceivedTime = new AtomicReference<>(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled).setMessageId(messageId); CountDownLatch countDownLatch = new CountDownLatch(2); setSender(entityType, entityIndex, isSessionEnabled); sendMessage(message).block(TIMEOUT); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); AmqpRetryOptions amqpRetryOptions = new AmqpRetryOptions() .setTryTimeout(Duration.ofSeconds(2 * lockTimeoutDurationSeconds)); processor = getSessionProcessorBuilder(false, entityType, entityIndex, false, amqpRetryOptions) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } else { this.processor = getProcessorBuilder(false, entityType, entityIndex, false) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } processor.start(); if (countDownLatch.await(lockTimeoutDurationSeconds * 6, TimeUnit.SECONDS)) { logger.info("Message lock has been renewed. Now closing processor"); } else { Assertions.fail("Message not arrived, closing processor."); } processor.close(); }
class ServiceBusProcessorClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final Scheduler scheduler = Schedulers.parallel(); private ServiceBusProcessorClient processor; private ServiceBusSenderAsyncClient sender; @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(processor, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } ServiceBusProcessorClientIntegrationTest() { super(new ClientLogger(ServiceBusProcessorClientIntegrationTest.class)); } /** * Validate that processor receive the message and {@code MaxAutoLockRenewDuration} is set on the * {@link ServiceBusReceiverAsyncClient}. The message lock is released by the client and same message received * again. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest private void processMessage(ServiceBusReceivedMessageContext context, CountDownLatch countDownLatch, String expectedMessageId, AtomicReference<OffsetTime> lastMessageReceivedTime, int lockTimeoutDurationSeconds) { ServiceBusReceivedMessage message = context.getMessage(); if (message.getMessageId().equals(expectedMessageId)) { logger.info("Processing message. Session: {}, Sequence message.getSequenceNumber(), message.getBody()); if (lastMessageReceivedTime.get() == null) { lastMessageReceivedTime.set(OffsetTime.now()); countDownLatch.countDown(); } else { long messageReceivedAfterSeconds = Duration.between(lastMessageReceivedTime.get(), OffsetTime.now()).getSeconds(); logger.info("Processing message again. Session: {}, Sequence message.getSequenceNumber(), message.getBody(), messageReceivedAfterSeconds); if (messageReceivedAfterSeconds >= 2 * lockTimeoutDurationSeconds) { countDownLatch.countDown(); } } } else { logger.info("Received message, message id did not match. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); } } private void processError(ServiceBusErrorContext context, CountDownLatch countdownLatch) { logger.info("Error when receiving messages from namespace: {}. Entity: {}}", context.getFullyQualifiedNamespace(), context.getEntityPath()); }
class ServiceBusProcessorClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final Scheduler scheduler = Schedulers.parallel(); private ServiceBusProcessorClient processor; private ServiceBusSenderAsyncClient sender; @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(processor, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } ServiceBusProcessorClientIntegrationTest() { super(new ClientLogger(ServiceBusProcessorClientIntegrationTest.class)); } /** * Validate that processor receive the message and {@code MaxAutoLockRenewDuration} is set on the * {@link ServiceBusReceiverAsyncClient}. The message lock is released by the client and same message received * again. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest private void processMessage(ServiceBusReceivedMessageContext context, CountDownLatch countDownLatch, String expectedMessageId, AtomicReference<OffsetTime> lastMessageReceivedTime, int lockTimeoutDurationSeconds) { ServiceBusReceivedMessage message = context.getMessage(); if (message.getMessageId().equals(expectedMessageId)) { logger.info("Processing message. Session: {}, Sequence message.getSequenceNumber(), message.getBody()); if (lastMessageReceivedTime.get() == null) { lastMessageReceivedTime.set(OffsetTime.now()); countDownLatch.countDown(); } else { long messageReceivedAfterSeconds = Duration.between(lastMessageReceivedTime.get(), OffsetTime.now()).getSeconds(); logger.info("Processing message again. Session: {}, Sequence message.getSequenceNumber(), message.getBody(), messageReceivedAfterSeconds); if (messageReceivedAfterSeconds >= 2 * lockTimeoutDurationSeconds) { countDownLatch.countDown(); } } } else { logger.info("Received message, message id did not match. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); } } private void processError(ServiceBusErrorContext context, CountDownLatch countdownLatch) { logger.info("Error when receiving messages from namespace: {}. Entity: {}}", context.getFullyQualifiedNamespace(), context.getEntityPath()); }
'tryTimeoutDuration' is used as 'inactivity time' : means if there is no activity on link (no message arriving in this time), It will close the link. The is defaulted to 60 seconds for my test, so I am setting it to 30 seconds. https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusClientBuilder.java#L104
void receiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) throws InterruptedException { final int lockTimeoutDurationSeconds = 15; final int entityIndex = TestUtils.USE_CASE_PROCESSOR_RECEIVE; final Duration expectedMaxAutoLockRenew = Duration.ofSeconds(35); final String messageId = UUID.randomUUID().toString(); final AtomicReference<OffsetTime> lastMessageReceivedTime = new AtomicReference<>(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled).setMessageId(messageId); CountDownLatch countDownLatch = new CountDownLatch(2); setSender(entityType, entityIndex, isSessionEnabled); sendMessage(message).block(TIMEOUT); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); AmqpRetryOptions amqpRetryOptions = new AmqpRetryOptions() .setTryTimeout(Duration.ofSeconds(2 * lockTimeoutDurationSeconds)); processor = getSessionProcessorBuilder(false, entityType, entityIndex, false, amqpRetryOptions) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } else { this.processor = getProcessorBuilder(false, entityType, entityIndex, false) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } processor.start(); if (countDownLatch.await(lockTimeoutDurationSeconds * 6, TimeUnit.SECONDS)) { logger.info("Message lock has been renewed. Now closing processor"); } else { Assertions.fail("Message not arrived, closing processor."); } processor.close(); }
final int lockTimeoutDurationSeconds = 15;
void receiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) throws InterruptedException { final int lockTimeoutDurationSeconds = 15; final int entityIndex = TestUtils.USE_CASE_PROCESSOR_RECEIVE; final Duration expectedMaxAutoLockRenew = Duration.ofSeconds(35); final String messageId = UUID.randomUUID().toString(); final AtomicReference<OffsetTime> lastMessageReceivedTime = new AtomicReference<>(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled).setMessageId(messageId); CountDownLatch countDownLatch = new CountDownLatch(2); setSender(entityType, entityIndex, isSessionEnabled); sendMessage(message).block(TIMEOUT); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); AmqpRetryOptions amqpRetryOptions = new AmqpRetryOptions() .setTryTimeout(Duration.ofSeconds(2 * lockTimeoutDurationSeconds)); processor = getSessionProcessorBuilder(false, entityType, entityIndex, false, amqpRetryOptions) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } else { this.processor = getProcessorBuilder(false, entityType, entityIndex, false) .maxAutoLockRenewDuration(expectedMaxAutoLockRenew) .disableAutoComplete() .processMessage(context -> processMessage(context, countDownLatch, messageId, lastMessageReceivedTime, lockTimeoutDurationSeconds)) .processError(context -> processError(context, countDownLatch)) .buildProcessorClient(); } processor.start(); if (countDownLatch.await(lockTimeoutDurationSeconds * 6, TimeUnit.SECONDS)) { logger.info("Message lock has been renewed. Now closing processor"); } else { Assertions.fail("Message not arrived, closing processor."); } processor.close(); }
class ServiceBusProcessorClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final Scheduler scheduler = Schedulers.parallel(); private ServiceBusProcessorClient processor; private ServiceBusSenderAsyncClient sender; @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(processor, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } ServiceBusProcessorClientIntegrationTest() { super(new ClientLogger(ServiceBusProcessorClientIntegrationTest.class)); } /** * Validate that processor receive the message and {@code MaxAutoLockRenewDuration} is set on the * {@link ServiceBusReceiverAsyncClient}. The message lock is released by the client and same message received * again. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest private void processMessage(ServiceBusReceivedMessageContext context, CountDownLatch countDownLatch, String expectedMessageId, AtomicReference<OffsetTime> lastMessageReceivedTime, int lockTimeoutDurationSeconds) { ServiceBusReceivedMessage message = context.getMessage(); if (message.getMessageId().equals(expectedMessageId)) { logger.info("Processing message. Session: {}, Sequence message.getSequenceNumber(), message.getBody()); if (lastMessageReceivedTime.get() == null) { lastMessageReceivedTime.set(OffsetTime.now()); countDownLatch.countDown(); } else { long messageReceivedAfterSeconds = Duration.between(lastMessageReceivedTime.get(), OffsetTime.now()).getSeconds(); logger.info("Processing message again. Session: {}, Sequence message.getSequenceNumber(), message.getBody(), messageReceivedAfterSeconds); if (messageReceivedAfterSeconds >= 2 * lockTimeoutDurationSeconds) { countDownLatch.countDown(); } } } else { logger.info("Received message, message id did not match. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); } } private void processError(ServiceBusErrorContext context, CountDownLatch countdownLatch) { logger.info("Error when receiving messages from namespace: {}. Entity: {}}", context.getFullyQualifiedNamespace(), context.getEntityPath()); }
class ServiceBusProcessorClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final Scheduler scheduler = Schedulers.parallel(); private ServiceBusProcessorClient processor; private ServiceBusSenderAsyncClient sender; @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(processor, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } ServiceBusProcessorClientIntegrationTest() { super(new ClientLogger(ServiceBusProcessorClientIntegrationTest.class)); } /** * Validate that processor receive the message and {@code MaxAutoLockRenewDuration} is set on the * {@link ServiceBusReceiverAsyncClient}. The message lock is released by the client and same message received * again. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest private void processMessage(ServiceBusReceivedMessageContext context, CountDownLatch countDownLatch, String expectedMessageId, AtomicReference<OffsetTime> lastMessageReceivedTime, int lockTimeoutDurationSeconds) { ServiceBusReceivedMessage message = context.getMessage(); if (message.getMessageId().equals(expectedMessageId)) { logger.info("Processing message. Session: {}, Sequence message.getSequenceNumber(), message.getBody()); if (lastMessageReceivedTime.get() == null) { lastMessageReceivedTime.set(OffsetTime.now()); countDownLatch.countDown(); } else { long messageReceivedAfterSeconds = Duration.between(lastMessageReceivedTime.get(), OffsetTime.now()).getSeconds(); logger.info("Processing message again. Session: {}, Sequence message.getSequenceNumber(), message.getBody(), messageReceivedAfterSeconds); if (messageReceivedAfterSeconds >= 2 * lockTimeoutDurationSeconds) { countDownLatch.countDown(); } } } else { logger.info("Received message, message id did not match. Session: %s, Sequence message.getSequenceNumber(), message.getBody()); } } private void processError(ServiceBusErrorContext context, CountDownLatch countdownLatch) { logger.info("Error when receiving messages from namespace: {}. Entity: {}}", context.getFullyQualifiedNamespace(), context.getEntityPath()); }
Why do we need to check `isAutoCompleteEnabled` to clean up the auto-renew lock?
protected void hookOnNext(ServiceBusMessageContext messageContext) { final ServiceBusReceivedMessage message = messageContext.getMessage(); final Consumer<ServiceBusMessageContext> lockCleanup; if (message != null) { final String lockToken = message.getLockToken(); final OffsetDateTime lockedUntil = message.getLockedUntil(); final LockRenewalOperation renewOperation; if (Objects.isNull(lockToken)) { logger.warning("Unexpected, LockToken is not present in message. sequenceNumber[{}].", message.getSequenceNumber()); return; } else if (Objects.isNull(lockedUntil)) { logger.warning("Unexpected, lockedUntil is not present in message. sequenceNumber[{}].", message.getSequenceNumber()); return; } final Function<String, Mono<OffsetDateTime>> onRenewLockUpdateMessage = onRenewLock.andThen(updated -> updated.map(newLockedUntil -> { message.setLockedUntil(newLockedUntil); return newLockedUntil; })); renewOperation = new LockRenewalOperation(lockToken, maxAutoLockRenewal, false, onRenewLockUpdateMessage, lockedUntil); try { messageLockContainer.addOrUpdate(lockToken, OffsetDateTime.now().plus(maxAutoLockRenewal), renewOperation); } catch (Exception e) { logger.info("Exception occurred while updating lockContainer for token [{}].", lockToken, e); } lockCleanup = context -> { renewOperation.close(); messageLockContainer.remove(context.getMessage().getLockToken()); }; } else { lockCleanup = LOCK_RENEW_NO_OP; } try { actual.onNext(messageContext); } catch (Exception e) { logger.info("Exception occurred while handling downstream onNext operation.", e); } finally { if (isAutoCompleteEnabled) { lockCleanup.accept(messageContext); } } }
}
protected void hookOnNext(ServiceBusMessageContext messageContext) { final ServiceBusReceivedMessage message = messageContext.getMessage(); final Consumer<ServiceBusMessageContext> lockCleanup; if (message != null) { final String lockToken = message.getLockToken(); final OffsetDateTime lockedUntil = message.getLockedUntil(); final LockRenewalOperation renewOperation; if (Objects.isNull(lockToken)) { logger.warning("Unexpected, LockToken is not present in message. sequenceNumber[{}].", message.getSequenceNumber()); return; } else if (Objects.isNull(lockedUntil)) { logger.warning("Unexpected, lockedUntil is not present in message. sequenceNumber[{}].", message.getSequenceNumber()); return; } final Function<String, Mono<OffsetDateTime>> onRenewLockUpdateMessage = onRenewLock.andThen(updated -> updated.map(newLockedUntil -> { message.setLockedUntil(newLockedUntil); return newLockedUntil; })); renewOperation = new LockRenewalOperation(lockToken, maxAutoLockRenewal, false, onRenewLockUpdateMessage, lockedUntil); try { messageLockContainer.addOrUpdate(lockToken, OffsetDateTime.now().plus(maxAutoLockRenewal), renewOperation); } catch (Exception e) { logger.info("Exception occurred while updating lockContainer for token [{}].", lockToken, e); } lockCleanup = context -> { renewOperation.close(); messageLockContainer.remove(context.getMessage().getLockToken()); }; } else { lockCleanup = LOCK_RENEW_NO_OP; } try { actual.onNext(messageContext); } catch (Exception e) { logger.info("Exception occurred while handling downstream onNext operation.", e); } finally { if (isAutoCompleteEnabled) { lockCleanup.accept(messageContext); } } }
class LockRenewSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private static final Consumer<ServiceBusMessageContext> LOCK_RENEW_NO_OP = messageContext -> { }; private final ClientLogger logger = new ClientLogger(LockRenewSubscriber.class); private final Function<String, Mono<OffsetDateTime>> onRenewLock; private final Duration maxAutoLockRenewal; private final LockContainer<LockRenewalOperation> messageLockContainer; private final CoreSubscriber<? super ServiceBusMessageContext> actual; private final boolean isAutoCompleteEnabled; LockRenewSubscriber(CoreSubscriber<? super ServiceBusMessageContext> actual, Duration maxAutoLockRenewDuration, LockContainer<LockRenewalOperation> messageLockContainer, Function<String, Mono<OffsetDateTime>> onRenewLock, boolean isAutoCompleteEnabled) { this.onRenewLock = Objects.requireNonNull(onRenewLock, "'onRenewLock' cannot be null."); this.actual = Objects.requireNonNull(actual, "'downstream' cannot be null."); this.messageLockContainer = Objects.requireNonNull(messageLockContainer, "'messageLockContainer' cannot be null."); this.maxAutoLockRenewal = Objects.requireNonNull(maxAutoLockRenewDuration, "'maxAutoLockRenewDuration' cannot be null."); this.isAutoCompleteEnabled = isAutoCompleteEnabled; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { Objects.requireNonNull(subscription, "'subscription' cannot be null."); actual.onSubscribe(subscription); } /** * When upstream has completed emitting messages. */ @Override public void hookOnComplete() { logger.verbose("Upstream has completed."); actual.onComplete(); } @Override protected void hookOnError(Throwable throwable) { logger.error("Errors occurred upstream.", throwable); actual.onError(throwable); } @Override @Override public Context currentContext() { return actual.currentContext(); } }
class LockRenewSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private static final Consumer<ServiceBusMessageContext> LOCK_RENEW_NO_OP = messageContext -> { }; private final ClientLogger logger = new ClientLogger(LockRenewSubscriber.class); private final Function<String, Mono<OffsetDateTime>> onRenewLock; private final Duration maxAutoLockRenewal; private final LockContainer<LockRenewalOperation> messageLockContainer; private final CoreSubscriber<? super ServiceBusMessageContext> actual; private final boolean isAutoCompleteEnabled; LockRenewSubscriber(CoreSubscriber<? super ServiceBusMessageContext> actual, Duration maxAutoLockRenewDuration, LockContainer<LockRenewalOperation> messageLockContainer, Function<String, Mono<OffsetDateTime>> onRenewLock, boolean isAutoCompleteEnabled) { this.onRenewLock = Objects.requireNonNull(onRenewLock, "'onRenewLock' cannot be null."); this.actual = Objects.requireNonNull(actual, "'downstream' cannot be null."); this.messageLockContainer = Objects.requireNonNull(messageLockContainer, "'messageLockContainer' cannot be null."); this.maxAutoLockRenewal = Objects.requireNonNull(maxAutoLockRenewDuration, "'maxAutoLockRenewDuration' cannot be null."); this.isAutoCompleteEnabled = isAutoCompleteEnabled; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { Objects.requireNonNull(subscription, "'subscription' cannot be null."); actual.onSubscribe(subscription); } /** * When upstream has completed emitting messages. */ @Override public void hookOnComplete() { logger.verbose("Upstream has completed."); actual.onComplete(); } @Override protected void hookOnError(Throwable throwable) { logger.error("Errors occurred upstream.", throwable); actual.onError(throwable); } @Override @Override public Context currentContext() { return actual.currentContext(); } }
isAutoCompleteEnabled : If user has disabled autoComplete, we need lock renew to continue , we do not want to clean up in this case. When lock renew expire, it will be cleaned at that time.
protected void hookOnNext(ServiceBusMessageContext messageContext) { final ServiceBusReceivedMessage message = messageContext.getMessage(); final Consumer<ServiceBusMessageContext> lockCleanup; if (message != null) { final String lockToken = message.getLockToken(); final OffsetDateTime lockedUntil = message.getLockedUntil(); final LockRenewalOperation renewOperation; if (Objects.isNull(lockToken)) { logger.warning("Unexpected, LockToken is not present in message. sequenceNumber[{}].", message.getSequenceNumber()); return; } else if (Objects.isNull(lockedUntil)) { logger.warning("Unexpected, lockedUntil is not present in message. sequenceNumber[{}].", message.getSequenceNumber()); return; } final Function<String, Mono<OffsetDateTime>> onRenewLockUpdateMessage = onRenewLock.andThen(updated -> updated.map(newLockedUntil -> { message.setLockedUntil(newLockedUntil); return newLockedUntil; })); renewOperation = new LockRenewalOperation(lockToken, maxAutoLockRenewal, false, onRenewLockUpdateMessage, lockedUntil); try { messageLockContainer.addOrUpdate(lockToken, OffsetDateTime.now().plus(maxAutoLockRenewal), renewOperation); } catch (Exception e) { logger.info("Exception occurred while updating lockContainer for token [{}].", lockToken, e); } lockCleanup = context -> { renewOperation.close(); messageLockContainer.remove(context.getMessage().getLockToken()); }; } else { lockCleanup = LOCK_RENEW_NO_OP; } try { actual.onNext(messageContext); } catch (Exception e) { logger.info("Exception occurred while handling downstream onNext operation.", e); } finally { if (isAutoCompleteEnabled) { lockCleanup.accept(messageContext); } } }
}
protected void hookOnNext(ServiceBusMessageContext messageContext) { final ServiceBusReceivedMessage message = messageContext.getMessage(); final Consumer<ServiceBusMessageContext> lockCleanup; if (message != null) { final String lockToken = message.getLockToken(); final OffsetDateTime lockedUntil = message.getLockedUntil(); final LockRenewalOperation renewOperation; if (Objects.isNull(lockToken)) { logger.warning("Unexpected, LockToken is not present in message. sequenceNumber[{}].", message.getSequenceNumber()); return; } else if (Objects.isNull(lockedUntil)) { logger.warning("Unexpected, lockedUntil is not present in message. sequenceNumber[{}].", message.getSequenceNumber()); return; } final Function<String, Mono<OffsetDateTime>> onRenewLockUpdateMessage = onRenewLock.andThen(updated -> updated.map(newLockedUntil -> { message.setLockedUntil(newLockedUntil); return newLockedUntil; })); renewOperation = new LockRenewalOperation(lockToken, maxAutoLockRenewal, false, onRenewLockUpdateMessage, lockedUntil); try { messageLockContainer.addOrUpdate(lockToken, OffsetDateTime.now().plus(maxAutoLockRenewal), renewOperation); } catch (Exception e) { logger.info("Exception occurred while updating lockContainer for token [{}].", lockToken, e); } lockCleanup = context -> { renewOperation.close(); messageLockContainer.remove(context.getMessage().getLockToken()); }; } else { lockCleanup = LOCK_RENEW_NO_OP; } try { actual.onNext(messageContext); } catch (Exception e) { logger.info("Exception occurred while handling downstream onNext operation.", e); } finally { if (isAutoCompleteEnabled) { lockCleanup.accept(messageContext); } } }
class LockRenewSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private static final Consumer<ServiceBusMessageContext> LOCK_RENEW_NO_OP = messageContext -> { }; private final ClientLogger logger = new ClientLogger(LockRenewSubscriber.class); private final Function<String, Mono<OffsetDateTime>> onRenewLock; private final Duration maxAutoLockRenewal; private final LockContainer<LockRenewalOperation> messageLockContainer; private final CoreSubscriber<? super ServiceBusMessageContext> actual; private final boolean isAutoCompleteEnabled; LockRenewSubscriber(CoreSubscriber<? super ServiceBusMessageContext> actual, Duration maxAutoLockRenewDuration, LockContainer<LockRenewalOperation> messageLockContainer, Function<String, Mono<OffsetDateTime>> onRenewLock, boolean isAutoCompleteEnabled) { this.onRenewLock = Objects.requireNonNull(onRenewLock, "'onRenewLock' cannot be null."); this.actual = Objects.requireNonNull(actual, "'downstream' cannot be null."); this.messageLockContainer = Objects.requireNonNull(messageLockContainer, "'messageLockContainer' cannot be null."); this.maxAutoLockRenewal = Objects.requireNonNull(maxAutoLockRenewDuration, "'maxAutoLockRenewDuration' cannot be null."); this.isAutoCompleteEnabled = isAutoCompleteEnabled; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { Objects.requireNonNull(subscription, "'subscription' cannot be null."); actual.onSubscribe(subscription); } /** * When upstream has completed emitting messages. */ @Override public void hookOnComplete() { logger.verbose("Upstream has completed."); actual.onComplete(); } @Override protected void hookOnError(Throwable throwable) { logger.error("Errors occurred upstream.", throwable); actual.onError(throwable); } @Override @Override public Context currentContext() { return actual.currentContext(); } }
class LockRenewSubscriber extends BaseSubscriber<ServiceBusMessageContext> { private static final Consumer<ServiceBusMessageContext> LOCK_RENEW_NO_OP = messageContext -> { }; private final ClientLogger logger = new ClientLogger(LockRenewSubscriber.class); private final Function<String, Mono<OffsetDateTime>> onRenewLock; private final Duration maxAutoLockRenewal; private final LockContainer<LockRenewalOperation> messageLockContainer; private final CoreSubscriber<? super ServiceBusMessageContext> actual; private final boolean isAutoCompleteEnabled; LockRenewSubscriber(CoreSubscriber<? super ServiceBusMessageContext> actual, Duration maxAutoLockRenewDuration, LockContainer<LockRenewalOperation> messageLockContainer, Function<String, Mono<OffsetDateTime>> onRenewLock, boolean isAutoCompleteEnabled) { this.onRenewLock = Objects.requireNonNull(onRenewLock, "'onRenewLock' cannot be null."); this.actual = Objects.requireNonNull(actual, "'downstream' cannot be null."); this.messageLockContainer = Objects.requireNonNull(messageLockContainer, "'messageLockContainer' cannot be null."); this.maxAutoLockRenewal = Objects.requireNonNull(maxAutoLockRenewDuration, "'maxAutoLockRenewDuration' cannot be null."); this.isAutoCompleteEnabled = isAutoCompleteEnabled; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { Objects.requireNonNull(subscription, "'subscription' cannot be null."); actual.onSubscribe(subscription); } /** * When upstream has completed emitting messages. */ @Override public void hookOnComplete() { logger.verbose("Upstream has completed."); actual.onComplete(); } @Override protected void hookOnError(Throwable throwable) { logger.error("Errors occurred upstream.", throwable); actual.onError(throwable); } @Override @Override public Context currentContext() { return actual.currentContext(); } }
Sample code to list connection and approve it.
public void testPrivateEndpoint() { String saName2 = generateRandomResourceName("sa", 10); String peName2 = generateRandomResourceName("pe", 10); String pecName2 = generateRandomResourceName("pec", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(storageAccount) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .withManualApproval("request message") .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request message", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); List<PrivateEndpointConnection> storageAccountConnections = storageAccount.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, storageAccountConnections.size()); PrivateEndpointConnection storageAccountConnection = storageAccountConnections.iterator().next(); storageAccount.approvePrivateEndpointConnection(storageAccountConnection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); StorageAccount storageAccount2 = azureResourceManager.storageAccounts().define(saName2) .withRegion(region) .withNewResourceGroup(rgName) .create(); privateEndpoint.update() .updatePrivateLinkServiceConnection(pecName) .withRequestMessage("request2") .parent() .apply(); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request2", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); privateEndpoint.update() .withoutPrivateLinkServiceConnection(pecName) .definePrivateLinkServiceConnection(pecName2) .withResource(storageAccount2) .withSubResource(PrivateLinkSubResourceName.STORAGE_FILE) .attach() .apply(); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_FILE), privateEndpoint.privateLinkServiceConnections().get(pecName2).subResourceNames()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName2).state().status()); azureResourceManager.privateEndpoints().deleteById(privateEndpoint.id()); privateEndpoint = azureResourceManager.privateEndpoints().define(peName2) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); List<PrivateEndpoint> privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList()); Assertions.assertEquals(1, privateEndpoints.size()); Assertions.assertEquals(peName2, privateEndpoints.get(0).name()); }
storageAccount.approvePrivateEndpointConnection(storageAccountConnection.name());
public void testPrivateEndpoint() { String saName2 = generateRandomResourceName("sa", 10); String peName2 = generateRandomResourceName("pe", 10); String pecName2 = generateRandomResourceName("pec", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(storageAccount) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .withManualApproval("request message") .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request message", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); List<PrivateEndpointConnection> storageAccountConnections = storageAccount.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, storageAccountConnections.size()); PrivateEndpointConnection storageAccountConnection = storageAccountConnections.iterator().next(); Assertions.assertNotNull(storageAccountConnection.id()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint().id()); Assertions.assertNotNull(storageAccountConnection.privateLinkServiceConnectionState()); Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, storageAccountConnection.privateLinkServiceConnectionState().status()); storageAccount.approvePrivateEndpointConnection(storageAccountConnection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); StorageAccount storageAccount2 = azureResourceManager.storageAccounts().define(saName2) .withRegion(region) .withNewResourceGroup(rgName) .create(); privateEndpoint.update() .updatePrivateLinkServiceConnection(pecName) .withRequestMessage("request2") .parent() .apply(); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request2", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); privateEndpoint.update() .withoutPrivateLinkServiceConnection(pecName) .definePrivateLinkServiceConnection(pecName2) .withResource(storageAccount2) .withSubResource(PrivateLinkSubResourceName.STORAGE_FILE) .attach() .apply(); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_FILE), privateEndpoint.privateLinkServiceConnections().get(pecName2).subResourceNames()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName2).state().status()); azureResourceManager.privateEndpoints().deleteById(privateEndpoint.id()); privateEndpoint = azureResourceManager.privateEndpoints().define(peName2) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); List<PrivateEndpoint> privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList()); Assertions.assertEquals(1, privateEndpoints.size()); Assertions.assertEquals(peName2, privateEndpoints.get(0).name()); }
class PrivateLinkTests extends ResourceManagerTestBase { private AzureResourceManager azureResourceManager; private String rgName; private String saName; private String peName; private String vnName; private String subnetName; private String pecName; private final Region region = Region.US_EAST; private final String vnAddressSpace = "10.0.0.0/28"; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = buildManager(AzureResourceManager.class, httpPipeline, profile); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("sa", 10); vnName = generateRandomResourceName("vn", 10); subnetName = "default"; peName = generateRandomResourceName("pe", 10); pecName = generateRandomResourceName("pec", 10); } @Override protected void cleanUpResources() { try { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (Exception e) { } } @Test @Test public void testPrivateEndpointE2E() { final boolean validateOnVirtualMachine = true; String vnlName = generateRandomResourceName("vnl", 10); String pdzgName = "default"; String pdzcName = generateRandomResourceName("pdzcName", 10); String pdzcName2 = generateRandomResourceName("pdzcName", 10); String vmName = generateRandomResourceName("vm", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); VirtualMachine virtualMachine = null; if (validateOnVirtualMachine) { virtualMachine = azureResourceManager.virtualMachines().define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet(subnetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testUser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define("privatelink.blob.core.windows.net") .withExistingResourceGroup(rgName) .defineARecordSet(saName) .withIPv4Address(privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0)) .attach() .defineVirtualNetworkLink(vnlName) .withVirtualNetworkId(network.id()) .attach() .create(); PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups().define(pdzgName) .withPrivateDnsZoneConfigure(pdzcName, privateDnsZone.id()) .create(); if (validateOnVirtualMachine) { RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } Assertions.assertEquals(1, privateEndpoint.privateDnsZoneGroups().list().stream().count()); Assertions.assertEquals(pdzgName, privateEndpoint.privateDnsZoneGroups().getById(privateDnsZoneGroup.id()).name()); PrivateDnsZone privateDnsZone2 = azureResourceManager.privateDnsZones().define("link.blob.core.windows.net") .withExistingResourceGroup(rgName) .create(); privateDnsZoneGroup.update() .withoutPrivateDnsZoneConfigure(pdzcName) .withPrivateDnsZoneConfigure(pdzcName2, privateDnsZone2.id()) .apply(); privateEndpoint.privateDnsZoneGroups().deleteById(privateDnsZoneGroup.id()); } @Test public void testStoragePrivateLinkResources() { StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); PagedIterable<PrivateLinkResource> privateLinkResources = storageAccount.listPrivateLinkResources(); List<PrivateLinkResource> privateLinkResourceList = privateLinkResources.stream().collect(Collectors.toList()); Assertions.assertFalse(privateLinkResourceList.isEmpty()); Assertions.assertTrue(privateLinkResourceList.stream().anyMatch(r -> "blob".equals(r.groupId()))); } }
class PrivateLinkTests extends ResourceManagerTestBase { private AzureResourceManager azureResourceManager; private String rgName; private String saName; private String peName; private String vnName; private String subnetName; private String pecName; private final Region region = Region.US_EAST; private final String vnAddressSpace = "10.0.0.0/28"; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = buildManager(AzureResourceManager.class, httpPipeline, profile); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("sa", 10); vnName = generateRandomResourceName("vn", 10); subnetName = "default"; peName = generateRandomResourceName("pe", 10); pecName = generateRandomResourceName("pec", 10); } @Override protected void cleanUpResources() { try { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (Exception e) { } } @Test @Test public void testPrivateEndpointE2E() { final boolean validateOnVirtualMachine = true; String vnlName = generateRandomResourceName("vnl", 10); String pdzgName = "default"; String pdzcName = generateRandomResourceName("pdzcName", 10); String pdzcName2 = generateRandomResourceName("pdzcName", 10); String vmName = generateRandomResourceName("vm", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); VirtualMachine virtualMachine = null; if (validateOnVirtualMachine) { virtualMachine = azureResourceManager.virtualMachines().define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet(subnetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testUser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define("privatelink.blob.core.windows.net") .withExistingResourceGroup(rgName) .defineARecordSet(saName) .withIPv4Address(privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0)) .attach() .defineVirtualNetworkLink(vnlName) .withVirtualNetworkId(network.id()) .attach() .create(); PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups().define(pdzgName) .withPrivateDnsZoneConfigure(pdzcName, privateDnsZone.id()) .create(); if (validateOnVirtualMachine) { RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } Assertions.assertEquals(1, privateEndpoint.privateDnsZoneGroups().list().stream().count()); Assertions.assertEquals(pdzgName, privateEndpoint.privateDnsZoneGroups().getById(privateDnsZoneGroup.id()).name()); PrivateDnsZone privateDnsZone2 = azureResourceManager.privateDnsZones().define("link.blob.core.windows.net") .withExistingResourceGroup(rgName) .create(); privateDnsZoneGroup.update() .withoutPrivateDnsZoneConfigure(pdzcName) .withPrivateDnsZoneConfigure(pdzcName2, privateDnsZone2.id()) .apply(); privateEndpoint.privateDnsZoneGroups().deleteById(privateDnsZoneGroup.id()); } @Test public void testStoragePrivateLinkResources() { StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); validatePrivateLinkResource(storageAccount, PrivateLinkSubResourceName.STORAGE_BLOB.toString()); } @Test public void testPrivateEndpointVault() { String vaultName = generateRandomResourceName("vault", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.VAULT; Vault vault = azureResourceManager.vaults().define(vaultName) .withRegion(region) .withNewResourceGroup(rgName) .withEmptyAccessPolicy() .create(); validatePrivateLinkResource(vault, subResourceName.toString()); validateApprovePrivatePrivateEndpointConnection(vault, subResourceName); } @Test public void testPrivateEndpointCosmos() { String cosmosName = generateRandomResourceName("cosmos", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.COSMOS_SQL; CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(cosmosName) .withRegion(region) .withNewResourceGroup(rgName) .withDataModelSql() .withStrongConsistency() .create(); PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(cosmosDBAccount, subResourceName); com.azure.resourcemanager.cosmos.models.PrivateEndpointConnection connection = cosmosDBAccount.listPrivateEndpointConnection().values().iterator().next(); cosmosDBAccount.approvePrivateEndpointConnection(connection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } private void validatePrivateLinkResource(SupportsListingPrivateLinkResource resource, String requiredGroupId) { PagedIterable<PrivateLinkResource> privateLinkResources = resource.listPrivateLinkResources(); List<PrivateLinkResource> privateLinkResourceList = privateLinkResources.stream().collect(Collectors.toList()); Assertions.assertFalse(privateLinkResourceList.isEmpty()); Assertions.assertTrue(privateLinkResourceList.stream().anyMatch(r -> requiredGroupId.equals(r.groupId()))); } private PrivateEndpoint createPrivateEndpointForManualApproval(Resource resource, PrivateLinkSubResourceName subResourceName) { Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(resource) .withSubResource(subResourceName) .withManualApproval("request message") .attach() .create(); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); return privateEndpoint; } private <T extends Resource & SupportsUpdatingPrivateEndpointConnection> void validateApprovePrivatePrivateEndpointConnection( T resource, PrivateLinkSubResourceName subResourceName) { PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(resource, subResourceName); resource.approvePrivateEndpointConnection(pecName); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } }
Sample code to list private link resources.
public void testStoragePrivateLinkResources() { StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); PagedIterable<PrivateLinkResource> privateLinkResources = storageAccount.listPrivateLinkResources(); List<PrivateLinkResource> privateLinkResourceList = privateLinkResources.stream().collect(Collectors.toList()); Assertions.assertFalse(privateLinkResourceList.isEmpty()); Assertions.assertTrue(privateLinkResourceList.stream().anyMatch(r -> "blob".equals(r.groupId()))); }
List<PrivateLinkResource> privateLinkResourceList = privateLinkResources.stream().collect(Collectors.toList());
public void testStoragePrivateLinkResources() { StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); validatePrivateLinkResource(storageAccount, PrivateLinkSubResourceName.STORAGE_BLOB.toString()); }
class PrivateLinkTests extends ResourceManagerTestBase { private AzureResourceManager azureResourceManager; private String rgName; private String saName; private String peName; private String vnName; private String subnetName; private String pecName; private final Region region = Region.US_EAST; private final String vnAddressSpace = "10.0.0.0/28"; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = buildManager(AzureResourceManager.class, httpPipeline, profile); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("sa", 10); vnName = generateRandomResourceName("vn", 10); subnetName = "default"; peName = generateRandomResourceName("pe", 10); pecName = generateRandomResourceName("pec", 10); } @Override protected void cleanUpResources() { try { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (Exception e) { } } @Test public void testPrivateEndpoint() { String saName2 = generateRandomResourceName("sa", 10); String peName2 = generateRandomResourceName("pe", 10); String pecName2 = generateRandomResourceName("pec", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(storageAccount) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .withManualApproval("request message") .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request message", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); List<PrivateEndpointConnection> storageAccountConnections = storageAccount.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, storageAccountConnections.size()); PrivateEndpointConnection storageAccountConnection = storageAccountConnections.iterator().next(); storageAccount.approvePrivateEndpointConnection(storageAccountConnection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); StorageAccount storageAccount2 = azureResourceManager.storageAccounts().define(saName2) .withRegion(region) .withNewResourceGroup(rgName) .create(); privateEndpoint.update() .updatePrivateLinkServiceConnection(pecName) .withRequestMessage("request2") .parent() .apply(); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request2", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); privateEndpoint.update() .withoutPrivateLinkServiceConnection(pecName) .definePrivateLinkServiceConnection(pecName2) .withResource(storageAccount2) .withSubResource(PrivateLinkSubResourceName.STORAGE_FILE) .attach() .apply(); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_FILE), privateEndpoint.privateLinkServiceConnections().get(pecName2).subResourceNames()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName2).state().status()); azureResourceManager.privateEndpoints().deleteById(privateEndpoint.id()); privateEndpoint = azureResourceManager.privateEndpoints().define(peName2) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); List<PrivateEndpoint> privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList()); Assertions.assertEquals(1, privateEndpoints.size()); Assertions.assertEquals(peName2, privateEndpoints.get(0).name()); } @Test public void testPrivateEndpointE2E() { final boolean validateOnVirtualMachine = true; String vnlName = generateRandomResourceName("vnl", 10); String pdzgName = "default"; String pdzcName = generateRandomResourceName("pdzcName", 10); String pdzcName2 = generateRandomResourceName("pdzcName", 10); String vmName = generateRandomResourceName("vm", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); VirtualMachine virtualMachine = null; if (validateOnVirtualMachine) { virtualMachine = azureResourceManager.virtualMachines().define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet(subnetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testUser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define("privatelink.blob.core.windows.net") .withExistingResourceGroup(rgName) .defineARecordSet(saName) .withIPv4Address(privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0)) .attach() .defineVirtualNetworkLink(vnlName) .withVirtualNetworkId(network.id()) .attach() .create(); PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups().define(pdzgName) .withPrivateDnsZoneConfigure(pdzcName, privateDnsZone.id()) .create(); if (validateOnVirtualMachine) { RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } Assertions.assertEquals(1, privateEndpoint.privateDnsZoneGroups().list().stream().count()); Assertions.assertEquals(pdzgName, privateEndpoint.privateDnsZoneGroups().getById(privateDnsZoneGroup.id()).name()); PrivateDnsZone privateDnsZone2 = azureResourceManager.privateDnsZones().define("link.blob.core.windows.net") .withExistingResourceGroup(rgName) .create(); privateDnsZoneGroup.update() .withoutPrivateDnsZoneConfigure(pdzcName) .withPrivateDnsZoneConfigure(pdzcName2, privateDnsZone2.id()) .apply(); privateEndpoint.privateDnsZoneGroups().deleteById(privateDnsZoneGroup.id()); } @Test }
class PrivateLinkTests extends ResourceManagerTestBase { private AzureResourceManager azureResourceManager; private String rgName; private String saName; private String peName; private String vnName; private String subnetName; private String pecName; private final Region region = Region.US_EAST; private final String vnAddressSpace = "10.0.0.0/28"; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = buildManager(AzureResourceManager.class, httpPipeline, profile); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("sa", 10); vnName = generateRandomResourceName("vn", 10); subnetName = "default"; peName = generateRandomResourceName("pe", 10); pecName = generateRandomResourceName("pec", 10); } @Override protected void cleanUpResources() { try { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (Exception e) { } } @Test public void testPrivateEndpoint() { String saName2 = generateRandomResourceName("sa", 10); String peName2 = generateRandomResourceName("pe", 10); String pecName2 = generateRandomResourceName("pec", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(storageAccount) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .withManualApproval("request message") .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request message", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); List<PrivateEndpointConnection> storageAccountConnections = storageAccount.listPrivateEndpointConnections().stream().collect(Collectors.toList()); Assertions.assertEquals(1, storageAccountConnections.size()); PrivateEndpointConnection storageAccountConnection = storageAccountConnections.iterator().next(); Assertions.assertNotNull(storageAccountConnection.id()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint()); Assertions.assertNotNull(storageAccountConnection.privateEndpoint().id()); Assertions.assertNotNull(storageAccountConnection.privateLinkServiceConnectionState()); Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, storageAccountConnection.privateLinkServiceConnectionState().status()); storageAccount.approvePrivateEndpointConnection(storageAccountConnection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); StorageAccount storageAccount2 = azureResourceManager.storageAccounts().define(saName2) .withRegion(region) .withNewResourceGroup(rgName) .create(); privateEndpoint.update() .updatePrivateLinkServiceConnection(pecName) .withRequestMessage("request2") .parent() .apply(); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); Assertions.assertEquals("request2", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage()); privateEndpoint.update() .withoutPrivateLinkServiceConnection(pecName) .definePrivateLinkServiceConnection(pecName2) .withResource(storageAccount2) .withSubResource(PrivateLinkSubResourceName.STORAGE_FILE) .attach() .apply(); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_FILE), privateEndpoint.privateLinkServiceConnections().get(pecName2).subResourceNames()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName2).state().status()); azureResourceManager.privateEndpoints().deleteById(privateEndpoint.id()); privateEndpoint = azureResourceManager.privateEndpoints().define(peName2) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); List<PrivateEndpoint> privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList()); Assertions.assertEquals(1, privateEndpoints.size()); Assertions.assertEquals(peName2, privateEndpoints.get(0).name()); } @Test public void testPrivateEndpointE2E() { final boolean validateOnVirtualMachine = true; String vnlName = generateRandomResourceName("vnl", 10); String pdzgName = "default"; String pdzcName = generateRandomResourceName("pdzcName", 10); String pdzcName2 = generateRandomResourceName("pdzcName", 10); String vmName = generateRandomResourceName("vm", 10); String saDomainName = saName + ".blob.core.windows.net"; System.out.println("storage account domain name: " + saDomainName); StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) .withRegion(region) .withNewResourceGroup(rgName) .create(); Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnetId(network.subnets().get(subnetName).id()) .definePrivateLinkServiceConnection(pecName) .withResourceId(storageAccount.id()) .withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB) .attach() .create(); Assertions.assertNotNull(privateEndpoint.subnet()); Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id()); Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size()); Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size()); Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId()); Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames()); Assertions.assertNotNull(privateEndpoint.customDnsConfigurations()); Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty()); Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval()); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0); System.out.println("storage account private ip: " + saPrivateIp); VirtualMachine virtualMachine = null; if (validateOnVirtualMachine) { virtualMachine = azureResourceManager.virtualMachines().define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withExistingPrimaryNetwork(network) .withSubnet(subnetName) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername("testUser") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4")) .create(); RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define("privatelink.blob.core.windows.net") .withExistingResourceGroup(rgName) .defineARecordSet(saName) .withIPv4Address(privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0)) .attach() .defineVirtualNetworkLink(vnlName) .withVirtualNetworkId(network.id()) .attach() .create(); PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups().define(pdzgName) .withPrivateDnsZoneConfigure(pdzcName, privateDnsZone.id()) .create(); if (validateOnVirtualMachine) { RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null); for (InstanceViewStatus status : commandResult.value()) { System.out.println(status.message()); } Assertions.assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp))); } Assertions.assertEquals(1, privateEndpoint.privateDnsZoneGroups().list().stream().count()); Assertions.assertEquals(pdzgName, privateEndpoint.privateDnsZoneGroups().getById(privateDnsZoneGroup.id()).name()); PrivateDnsZone privateDnsZone2 = azureResourceManager.privateDnsZones().define("link.blob.core.windows.net") .withExistingResourceGroup(rgName) .create(); privateDnsZoneGroup.update() .withoutPrivateDnsZoneConfigure(pdzcName) .withPrivateDnsZoneConfigure(pdzcName2, privateDnsZone2.id()) .apply(); privateEndpoint.privateDnsZoneGroups().deleteById(privateDnsZoneGroup.id()); } @Test @Test public void testPrivateEndpointVault() { String vaultName = generateRandomResourceName("vault", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.VAULT; Vault vault = azureResourceManager.vaults().define(vaultName) .withRegion(region) .withNewResourceGroup(rgName) .withEmptyAccessPolicy() .create(); validatePrivateLinkResource(vault, subResourceName.toString()); validateApprovePrivatePrivateEndpointConnection(vault, subResourceName); } @Test public void testPrivateEndpointCosmos() { String cosmosName = generateRandomResourceName("cosmos", 10); PrivateLinkSubResourceName subResourceName = PrivateLinkSubResourceName.COSMOS_SQL; CosmosDBAccount cosmosDBAccount = azureResourceManager.cosmosDBAccounts().define(cosmosName) .withRegion(region) .withNewResourceGroup(rgName) .withDataModelSql() .withStrongConsistency() .create(); PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(cosmosDBAccount, subResourceName); com.azure.resourcemanager.cosmos.models.PrivateEndpointConnection connection = cosmosDBAccount.listPrivateEndpointConnection().values().iterator().next(); cosmosDBAccount.approvePrivateEndpointConnection(connection.name()); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } private void validatePrivateLinkResource(SupportsListingPrivateLinkResource resource, String requiredGroupId) { PagedIterable<PrivateLinkResource> privateLinkResources = resource.listPrivateLinkResources(); List<PrivateLinkResource> privateLinkResourceList = privateLinkResources.stream().collect(Collectors.toList()); Assertions.assertFalse(privateLinkResourceList.isEmpty()); Assertions.assertTrue(privateLinkResourceList.stream().anyMatch(r -> requiredGroupId.equals(r.groupId()))); } private PrivateEndpoint createPrivateEndpointForManualApproval(Resource resource, PrivateLinkSubResourceName subResourceName) { Network network = azureResourceManager.networks().define(vnName) .withRegion(region) .withExistingResourceGroup(rgName) .withAddressSpace(vnAddressSpace) .defineSubnet(subnetName) .withAddressPrefix(vnAddressSpace) .disableNetworkPoliciesOnPrivateEndpoint() .attach() .create(); PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName) .withRegion(region) .withExistingResourceGroup(rgName) .withSubnet(network.subnets().get(subnetName)) .definePrivateLinkServiceConnection(pecName) .withResource(resource) .withSubResource(subResourceName) .withManualApproval("request message") .attach() .create(); Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); return privateEndpoint; } private <T extends Resource & SupportsUpdatingPrivateEndpointConnection> void validateApprovePrivatePrivateEndpointConnection( T resource, PrivateLinkSubResourceName subResourceName) { PrivateEndpoint privateEndpoint = createPrivateEndpointForManualApproval(resource, subResourceName); resource.approvePrivateEndpointConnection(pecName); privateEndpoint.refresh(); Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status()); } }
Can it be just `listByStorageAccountAsync`?
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); }
.listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name())
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); }
class StorageAccountImpl extends GroupableResourceImpl<StorageAccount, StorageAccountInner, StorageAccountImpl, StorageManager> implements StorageAccount, StorageAccount.Definition, StorageAccount.Update { private final ClientLogger logger = new ClientLogger(getClass()); private PublicEndpoints publicEndpoints; private AccountStatuses accountStatuses; private StorageAccountCreateParameters createParameters; private StorageAccountUpdateParameters updateParameters; private StorageNetworkRulesHelper networkRulesHelper; private StorageEncryptionHelper encryptionHelper; StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager) { super(name, innerModel, storageManager); this.createParameters = new StorageAccountCreateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.createParameters); this.encryptionHelper = new StorageEncryptionHelper(this.createParameters); } @Override public AccountStatuses accountStatuses() { if (accountStatuses == null) { accountStatuses = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); } return accountStatuses; } @Override public StorageAccountSkuType skuType() { return StorageAccountSkuType.fromSkuName(this.innerModel().sku().name()); } @Override public Kind kind() { return innerModel().kind(); } @Override public OffsetDateTime creationTime() { return this.innerModel().creationTime(); } @Override public CustomDomain customDomain() { return this.innerModel().customDomain(); } @Override public OffsetDateTime lastGeoFailoverTime() { return this.innerModel().lastGeoFailoverTime(); } @Override public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } @Override public PublicEndpoints endPoints() { if (publicEndpoints == null) { publicEndpoints = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); } return publicEndpoints; } @Override public StorageAccountEncryptionKeySource encryptionKeySource() { return StorageEncryptionHelper.encryptionKeySource(this.innerModel()); } @Override public Map<StorageService, StorageAccountEncryptionStatus> encryptionStatuses() { return StorageEncryptionHelper.encryptionStatuses(this.innerModel()); } @Override public AccessTier accessTier() { return innerModel().accessTier(); } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().tenantId(); } } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().principalId(); } } @Override public boolean isAccessAllowedFromAllNetworks() { return StorageNetworkRulesHelper.isAccessAllowedFromAllNetworks(this.innerModel()); } @Override public List<String> networkSubnetsWithAccess() { return StorageNetworkRulesHelper.networkSubnetsWithAccess(this.innerModel()); } @Override public List<String> ipAddressesWithAccess() { return StorageNetworkRulesHelper.ipAddressesWithAccess(this.innerModel()); } @Override public List<String> ipAddressRangesWithAccess() { return StorageNetworkRulesHelper.ipAddressRangesWithAccess(this.innerModel()); } @Override public boolean canReadLogEntriesFromAnyNetwork() { return StorageNetworkRulesHelper.canReadLogEntriesFromAnyNetwork(this.innerModel()); } @Override public boolean canReadMetricsFromAnyNetwork() { return StorageNetworkRulesHelper.canReadMetricsFromAnyNetwork(this.innerModel()); } @Override public boolean canAccessFromAzureServices() { return StorageNetworkRulesHelper.canAccessFromAzureServices(this.innerModel()); } @Override public boolean isAzureFilesAadIntegrationEnabled() { return this.innerModel().azureFilesIdentityBasedAuthentication() != null && this.innerModel().azureFilesIdentityBasedAuthentication().directoryServiceOptions() == DirectoryServiceOptions.AADDS; } @Override public boolean isHnsEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().isHnsEnabled()); } @Override public boolean isLargeFileSharesEnabled() { return this.innerModel().largeFileSharesState() == LargeFileSharesState.ENABLED; } @Override public MinimumTlsVersion minimumTlsVersion() { return this.innerModel().minimumTlsVersion(); } @Override public boolean isHttpsTrafficOnly() { if (this.innerModel().enableHttpsTrafficOnly() == null) { return true; } return this.innerModel().enableHttpsTrafficOnly(); } @Override public boolean isBlobPublicAccessAllowed() { if (this.innerModel().allowBlobPublicAccess() == null) { return true; } return this.innerModel().allowBlobPublicAccess(); } @Override public boolean isSharedKeyAccessAllowed() { if (this.innerModel().allowSharedKeyAccess() == null) { return true; } return this.innerModel().allowSharedKeyAccess(); } @Override public List<StorageAccountKey> getKeys() { return this.getKeysAsync().block(); } @Override public Mono<List<StorageAccountKey>> getKeysAsync() { return this .manager() .serviceClient() .getStorageAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public List<StorageAccountKey> regenerateKey(String keyName) { return this.regenerateKeyAsync(keyName).block(); } @Override public Mono<List<StorageAccountKey>> regenerateKeyAsync(String keyName) { return this .manager() .serviceClient() .getStorageAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), keyName) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @Override public void approvePrivateEndpointConnection(String privateEndpointConnectionName) { approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new com.azure.resourcemanager.storage.models.PrivateLinkServiceConnectionState() .withStatus( com.azure.resourcemanager.storage.models.PrivateEndpointServiceConnectionStatus.APPROVED)) .then(); } @Override public Mono<StorageAccount> refreshAsync() { return super .refreshAsync() .map( storageAccount -> { StorageAccountImpl impl = (StorageAccountImpl) storageAccount; impl.clearWrapperProperties(); return impl; }); } @Override protected Mono<StorageAccountInner> getInnerAsync() { return this.manager().serviceClient().getStorageAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public StorageAccountImpl withSku(StorageAccountSkuType sku) { if (isInCreateMode()) { createParameters.withSku(new Sku().withName(sku.name())); } else { updateParameters.withSku(new Sku().withName(sku.name())); } return this; } @Override public StorageAccountImpl withBlobStorageAccountKind() { createParameters.withKind(Kind.BLOB_STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKind() { createParameters.withKind(Kind.STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKindV2() { createParameters.withKind(Kind.STORAGE_V2); return this; } @Override public StorageAccountImpl withBlockBlobStorageAccountKind() { createParameters.withKind(Kind.BLOCK_BLOB_STORAGE); return this; } @Override public StorageAccountImpl withFileStorageAccountKind() { createParameters.withKind(Kind.FILE_STORAGE); return this; } @Override public StorageAccountImpl withBlobEncryption() { this.encryptionHelper.withBlobEncryption(); return this; } @Override public StorageAccountImpl withFileEncryption() { this.encryptionHelper.withFileEncryption(); return this; } @Override public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion) { this.encryptionHelper.withEncryptionKeyFromKeyVault(keyVaultUri, keyName, keyVersion); return this; } @Override public StorageAccountImpl withoutBlobEncryption() { this.encryptionHelper.withoutBlobEncryption(); return this; } @Override public StorageAccountImpl withoutFileEncryption() { this.encryptionHelper.withoutFileEncryption(); return this; } private void clearWrapperProperties() { accountStatuses = null; publicEndpoints = null; } @Override public StorageAccountImpl update() { createParameters = null; updateParameters = new StorageAccountUpdateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.updateParameters, this.innerModel()); this.encryptionHelper = new StorageEncryptionHelper(this.updateParameters, this.innerModel()); return super.update(); } @Override public StorageAccountImpl withCustomDomain(CustomDomain customDomain) { if (isInCreateMode()) { createParameters.withCustomDomain(customDomain); } else { updateParameters.withCustomDomain(customDomain); } return this; } @Override public StorageAccountImpl withCustomDomain(String name) { return withCustomDomain(new CustomDomain().withName(name)); } @Override public StorageAccountImpl withCustomDomain(String name, boolean useSubDomain) { return withCustomDomain(new CustomDomain().withName(name).withUseSubDomainName(useSubDomain)); } @Override public StorageAccountImpl withAccessTier(AccessTier accessTier) { if (isInCreateMode()) { createParameters.withAccessTier(accessTier); } else { if (this.innerModel().kind() != Kind.BLOB_STORAGE) { throw logger.logExceptionAsError(new UnsupportedOperationException( "Access tier can not be changed for general purpose storage accounts.")); } updateParameters.withAccessTier(accessTier); } return this; } @Override public StorageAccountImpl withSystemAssignedManagedServiceIdentity() { if (this.innerModel().identity() == null) { if (isInCreateMode()) { createParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } else { updateParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } } return this; } @Override public StorageAccountImpl withOnlyHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(true); } else { updateParameters.withEnableHttpsTrafficOnly(true); } return this; } @Override public StorageAccountImpl withHttpAndHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(false); } else { updateParameters.withEnableHttpsTrafficOnly(false); } return this; } @Override public StorageAccountImpl withMinimumTlsVersion(MinimumTlsVersion minimumTlsVersion) { if (isInCreateMode()) { createParameters.withMinimumTlsVersion(minimumTlsVersion); } else { updateParameters.withMinimumTlsVersion(minimumTlsVersion); } return this; } @Override public StorageAccountImpl enableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(true); } else { updateParameters.withAllowBlobPublicAccess(true); } return this; } @Override public StorageAccountImpl disableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(false); } else { updateParameters.withAllowBlobPublicAccess(false); } return this; } @Override public StorageAccountImpl enableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(true); } else { updateParameters.withAllowSharedKeyAccess(true); } return this; } @Override public StorageAccountImpl disableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(false); } else { updateParameters.withAllowSharedKeyAccess(false); } return this; } @Override public StorageAccountImpl withAccessFromAllNetworks() { this.networkRulesHelper.withAccessFromAllNetworks(); return this; } @Override public StorageAccountImpl withAccessFromSelectedNetworks() { this.networkRulesHelper.withAccessFromSelectedNetworks(); return this; } @Override public StorageAccountImpl withAccessFromNetworkSubnet(String subnetId) { this.networkRulesHelper.withAccessFromNetworkSubnet(subnetId); return this; } @Override public StorageAccountImpl withAccessFromIpAddress(String ipAddress) { this.networkRulesHelper.withAccessFromIpAddress(ipAddress); return this; } @Override public StorageAccountImpl withAccessFromIpAddressRange(String ipAddressCidr) { this.networkRulesHelper.withAccessFromIpAddressRange(ipAddressCidr); return this; } @Override public StorageAccountImpl withReadAccessToLogEntriesFromAnyNetwork() { this.networkRulesHelper.withReadAccessToLoggingFromAnyNetwork(); return this; } @Override public StorageAccountImpl withReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withReadAccessToMetricsFromAnyNetwork(); return this; } @Override public StorageAccountImpl withAccessFromAzureServices() { this.networkRulesHelper.withAccessAllowedFromAzureServices(); return this; } @Override public StorageAccountImpl withoutNetworkSubnetAccess(String subnetId) { this.networkRulesHelper.withoutNetworkSubnetAccess(subnetId); return this; } @Override public StorageAccountImpl withoutIpAddressAccess(String ipAddress) { this.networkRulesHelper.withoutIpAddressAccess(ipAddress); return this; } @Override public StorageAccountImpl withoutIpAddressRangeAccess(String ipAddressCidr) { this.networkRulesHelper.withoutIpAddressRangeAccess(ipAddressCidr); return this; } @Override public Update withoutReadAccessToLoggingFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToLoggingFromAnyNetwork(); return this; } @Override public Update withoutReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToMetricsFromAnyNetwork(); return this; } @Override public Update withoutAccessFromAzureServices() { this.networkRulesHelper.withoutAccessFromAzureServices(); return this; } @Override public Update upgradeToGeneralPurposeAccountKindV2() { updateParameters.withKind(Kind.STORAGE_V2); return this; } @Override public Mono<StorageAccount> createResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); createParameters.withLocation(this.regionName()); createParameters.withTags(this.innerModel().tags()); final StorageAccountsClient client = this.manager().serviceClient().getStorageAccounts(); return this .manager() .serviceClient() .getStorageAccounts() .createAsync(this.resourceGroupName(), this.name(), createParameters) .flatMap( storageAccountInner -> client .getByResourceGroupAsync(resourceGroupName(), this.name()) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties())); } @Override public Mono<StorageAccount> updateResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); updateParameters.withTags(this.innerModel().tags()); return this .manager() .serviceClient() .getStorageAccounts() .updateAsync(resourceGroupName(), this.name(), updateParameters) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties()); } @Override public StorageAccountImpl withAzureFilesAadIntegrationEnabled(boolean enabled) { if (isInCreateMode()) { if (enabled) { this .createParameters .withAzureFilesIdentityBasedAuthentication( new AzureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); } } else { if (this.createParameters.azureFilesIdentityBasedAuthentication() == null) { this .createParameters .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication()); } if (enabled) { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS); } else { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.NONE); } } return this; } @Override public StorageAccountImpl withLargeFileShares(boolean enabled) { if (isInCreateMode()) { if (enabled) { this.createParameters.withLargeFileSharesState(LargeFileSharesState.ENABLED); } else { this.createParameters.withLargeFileSharesState(LargeFileSharesState.DISABLED); } } return this; } @Override public StorageAccountImpl withHnsEnabled(boolean enabled) { this.createParameters.withIsHnsEnabled(enabled); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel; private PrivateLinkResourceImpl(com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.requiredZoneNames()); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; public PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class StorageAccountImpl extends GroupableResourceImpl<StorageAccount, StorageAccountInner, StorageAccountImpl, StorageManager> implements StorageAccount, StorageAccount.Definition, StorageAccount.Update { private final ClientLogger logger = new ClientLogger(getClass()); private PublicEndpoints publicEndpoints; private AccountStatuses accountStatuses; private StorageAccountCreateParameters createParameters; private StorageAccountUpdateParameters updateParameters; private StorageNetworkRulesHelper networkRulesHelper; private StorageEncryptionHelper encryptionHelper; StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager) { super(name, innerModel, storageManager); this.createParameters = new StorageAccountCreateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.createParameters); this.encryptionHelper = new StorageEncryptionHelper(this.createParameters); } @Override public AccountStatuses accountStatuses() { if (accountStatuses == null) { accountStatuses = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); } return accountStatuses; } @Override public StorageAccountSkuType skuType() { return StorageAccountSkuType.fromSkuName(this.innerModel().sku().name()); } @Override public Kind kind() { return innerModel().kind(); } @Override public OffsetDateTime creationTime() { return this.innerModel().creationTime(); } @Override public CustomDomain customDomain() { return this.innerModel().customDomain(); } @Override public OffsetDateTime lastGeoFailoverTime() { return this.innerModel().lastGeoFailoverTime(); } @Override public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } @Override public PublicEndpoints endPoints() { if (publicEndpoints == null) { publicEndpoints = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); } return publicEndpoints; } @Override public StorageAccountEncryptionKeySource encryptionKeySource() { return StorageEncryptionHelper.encryptionKeySource(this.innerModel()); } @Override public Map<StorageService, StorageAccountEncryptionStatus> encryptionStatuses() { return StorageEncryptionHelper.encryptionStatuses(this.innerModel()); } @Override public AccessTier accessTier() { return innerModel().accessTier(); } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().tenantId(); } } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().principalId(); } } @Override public boolean isAccessAllowedFromAllNetworks() { return StorageNetworkRulesHelper.isAccessAllowedFromAllNetworks(this.innerModel()); } @Override public List<String> networkSubnetsWithAccess() { return StorageNetworkRulesHelper.networkSubnetsWithAccess(this.innerModel()); } @Override public List<String> ipAddressesWithAccess() { return StorageNetworkRulesHelper.ipAddressesWithAccess(this.innerModel()); } @Override public List<String> ipAddressRangesWithAccess() { return StorageNetworkRulesHelper.ipAddressRangesWithAccess(this.innerModel()); } @Override public boolean canReadLogEntriesFromAnyNetwork() { return StorageNetworkRulesHelper.canReadLogEntriesFromAnyNetwork(this.innerModel()); } @Override public boolean canReadMetricsFromAnyNetwork() { return StorageNetworkRulesHelper.canReadMetricsFromAnyNetwork(this.innerModel()); } @Override public boolean canAccessFromAzureServices() { return StorageNetworkRulesHelper.canAccessFromAzureServices(this.innerModel()); } @Override public boolean isAzureFilesAadIntegrationEnabled() { return this.innerModel().azureFilesIdentityBasedAuthentication() != null && this.innerModel().azureFilesIdentityBasedAuthentication().directoryServiceOptions() == DirectoryServiceOptions.AADDS; } @Override public boolean isHnsEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().isHnsEnabled()); } @Override public boolean isLargeFileSharesEnabled() { return this.innerModel().largeFileSharesState() == LargeFileSharesState.ENABLED; } @Override public MinimumTlsVersion minimumTlsVersion() { return this.innerModel().minimumTlsVersion(); } @Override public boolean isHttpsTrafficOnly() { if (this.innerModel().enableHttpsTrafficOnly() == null) { return true; } return this.innerModel().enableHttpsTrafficOnly(); } @Override public boolean isBlobPublicAccessAllowed() { if (this.innerModel().allowBlobPublicAccess() == null) { return true; } return this.innerModel().allowBlobPublicAccess(); } @Override public boolean isSharedKeyAccessAllowed() { if (this.innerModel().allowSharedKeyAccess() == null) { return true; } return this.innerModel().allowSharedKeyAccess(); } @Override public List<StorageAccountKey> getKeys() { return this.getKeysAsync().block(); } @Override public Mono<List<StorageAccountKey>> getKeysAsync() { return this .manager() .serviceClient() .getStorageAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public List<StorageAccountKey> regenerateKey(String keyName) { return this.regenerateKeyAsync(keyName).block(); } @Override public Mono<List<StorageAccountKey>> regenerateKeyAsync(String keyName) { return this .manager() .serviceClient() .getStorageAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), keyName) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @Override public void approvePrivateEndpointConnection(String privateEndpointConnectionName) { approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new com.azure.resourcemanager.storage.models.PrivateLinkServiceConnectionState() .withStatus( com.azure.resourcemanager.storage.models.PrivateEndpointServiceConnectionStatus.APPROVED)) .then(); } @Override public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) { rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new PrivateLinkServiceConnectionState() .withStatus( PrivateEndpointServiceConnectionStatus.REJECTED)) .then(); } @Override public Mono<StorageAccount> refreshAsync() { return super .refreshAsync() .map( storageAccount -> { StorageAccountImpl impl = (StorageAccountImpl) storageAccount; impl.clearWrapperProperties(); return impl; }); } @Override protected Mono<StorageAccountInner> getInnerAsync() { return this.manager().serviceClient().getStorageAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public StorageAccountImpl withSku(StorageAccountSkuType sku) { if (isInCreateMode()) { createParameters.withSku(new Sku().withName(sku.name())); } else { updateParameters.withSku(new Sku().withName(sku.name())); } return this; } @Override public StorageAccountImpl withBlobStorageAccountKind() { createParameters.withKind(Kind.BLOB_STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKind() { createParameters.withKind(Kind.STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKindV2() { createParameters.withKind(Kind.STORAGE_V2); return this; } @Override public StorageAccountImpl withBlockBlobStorageAccountKind() { createParameters.withKind(Kind.BLOCK_BLOB_STORAGE); return this; } @Override public StorageAccountImpl withFileStorageAccountKind() { createParameters.withKind(Kind.FILE_STORAGE); return this; } @Override public StorageAccountImpl withBlobEncryption() { this.encryptionHelper.withBlobEncryption(); return this; } @Override public StorageAccountImpl withFileEncryption() { this.encryptionHelper.withFileEncryption(); return this; } @Override public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion) { this.encryptionHelper.withEncryptionKeyFromKeyVault(keyVaultUri, keyName, keyVersion); return this; } @Override public StorageAccountImpl withoutBlobEncryption() { this.encryptionHelper.withoutBlobEncryption(); return this; } @Override public StorageAccountImpl withoutFileEncryption() { this.encryptionHelper.withoutFileEncryption(); return this; } private void clearWrapperProperties() { accountStatuses = null; publicEndpoints = null; } @Override public StorageAccountImpl update() { createParameters = null; updateParameters = new StorageAccountUpdateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.updateParameters, this.innerModel()); this.encryptionHelper = new StorageEncryptionHelper(this.updateParameters, this.innerModel()); return super.update(); } @Override public StorageAccountImpl withCustomDomain(CustomDomain customDomain) { if (isInCreateMode()) { createParameters.withCustomDomain(customDomain); } else { updateParameters.withCustomDomain(customDomain); } return this; } @Override public StorageAccountImpl withCustomDomain(String name) { return withCustomDomain(new CustomDomain().withName(name)); } @Override public StorageAccountImpl withCustomDomain(String name, boolean useSubDomain) { return withCustomDomain(new CustomDomain().withName(name).withUseSubDomainName(useSubDomain)); } @Override public StorageAccountImpl withAccessTier(AccessTier accessTier) { if (isInCreateMode()) { createParameters.withAccessTier(accessTier); } else { if (this.innerModel().kind() != Kind.BLOB_STORAGE) { throw logger.logExceptionAsError(new UnsupportedOperationException( "Access tier can not be changed for general purpose storage accounts.")); } updateParameters.withAccessTier(accessTier); } return this; } @Override public StorageAccountImpl withSystemAssignedManagedServiceIdentity() { if (this.innerModel().identity() == null) { if (isInCreateMode()) { createParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } else { updateParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } } return this; } @Override public StorageAccountImpl withOnlyHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(true); } else { updateParameters.withEnableHttpsTrafficOnly(true); } return this; } @Override public StorageAccountImpl withHttpAndHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(false); } else { updateParameters.withEnableHttpsTrafficOnly(false); } return this; } @Override public StorageAccountImpl withMinimumTlsVersion(MinimumTlsVersion minimumTlsVersion) { if (isInCreateMode()) { createParameters.withMinimumTlsVersion(minimumTlsVersion); } else { updateParameters.withMinimumTlsVersion(minimumTlsVersion); } return this; } @Override public StorageAccountImpl enableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(true); } else { updateParameters.withAllowBlobPublicAccess(true); } return this; } @Override public StorageAccountImpl disableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(false); } else { updateParameters.withAllowBlobPublicAccess(false); } return this; } @Override public StorageAccountImpl enableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(true); } else { updateParameters.withAllowSharedKeyAccess(true); } return this; } @Override public StorageAccountImpl disableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(false); } else { updateParameters.withAllowSharedKeyAccess(false); } return this; } @Override public StorageAccountImpl withAccessFromAllNetworks() { this.networkRulesHelper.withAccessFromAllNetworks(); return this; } @Override public StorageAccountImpl withAccessFromSelectedNetworks() { this.networkRulesHelper.withAccessFromSelectedNetworks(); return this; } @Override public StorageAccountImpl withAccessFromNetworkSubnet(String subnetId) { this.networkRulesHelper.withAccessFromNetworkSubnet(subnetId); return this; } @Override public StorageAccountImpl withAccessFromIpAddress(String ipAddress) { this.networkRulesHelper.withAccessFromIpAddress(ipAddress); return this; } @Override public StorageAccountImpl withAccessFromIpAddressRange(String ipAddressCidr) { this.networkRulesHelper.withAccessFromIpAddressRange(ipAddressCidr); return this; } @Override public StorageAccountImpl withReadAccessToLogEntriesFromAnyNetwork() { this.networkRulesHelper.withReadAccessToLoggingFromAnyNetwork(); return this; } @Override public StorageAccountImpl withReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withReadAccessToMetricsFromAnyNetwork(); return this; } @Override public StorageAccountImpl withAccessFromAzureServices() { this.networkRulesHelper.withAccessAllowedFromAzureServices(); return this; } @Override public StorageAccountImpl withoutNetworkSubnetAccess(String subnetId) { this.networkRulesHelper.withoutNetworkSubnetAccess(subnetId); return this; } @Override public StorageAccountImpl withoutIpAddressAccess(String ipAddress) { this.networkRulesHelper.withoutIpAddressAccess(ipAddress); return this; } @Override public StorageAccountImpl withoutIpAddressRangeAccess(String ipAddressCidr) { this.networkRulesHelper.withoutIpAddressRangeAccess(ipAddressCidr); return this; } @Override public Update withoutReadAccessToLoggingFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToLoggingFromAnyNetwork(); return this; } @Override public Update withoutReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToMetricsFromAnyNetwork(); return this; } @Override public Update withoutAccessFromAzureServices() { this.networkRulesHelper.withoutAccessFromAzureServices(); return this; } @Override public Update upgradeToGeneralPurposeAccountKindV2() { updateParameters.withKind(Kind.STORAGE_V2); return this; } @Override public Mono<StorageAccount> createResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); createParameters.withLocation(this.regionName()); createParameters.withTags(this.innerModel().tags()); final StorageAccountsClient client = this.manager().serviceClient().getStorageAccounts(); return this .manager() .serviceClient() .getStorageAccounts() .createAsync(this.resourceGroupName(), this.name(), createParameters) .flatMap( storageAccountInner -> client .getByResourceGroupAsync(resourceGroupName(), this.name()) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties())); } @Override public Mono<StorageAccount> updateResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); updateParameters.withTags(this.innerModel().tags()); return this .manager() .serviceClient() .getStorageAccounts() .updateAsync(resourceGroupName(), this.name(), updateParameters) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties()); } @Override public StorageAccountImpl withAzureFilesAadIntegrationEnabled(boolean enabled) { if (isInCreateMode()) { if (enabled) { this .createParameters .withAzureFilesIdentityBasedAuthentication( new AzureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); } } else { if (this.createParameters.azureFilesIdentityBasedAuthentication() == null) { this .createParameters .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication()); } if (enabled) { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS); } else { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.NONE); } } return this; } @Override public StorageAccountImpl withLargeFileShares(boolean enabled) { if (isInCreateMode()) { if (enabled) { this.createParameters.withLargeFileSharesState(LargeFileSharesState.ENABLED); } else { this.createParameters.withLargeFileSharesState(LargeFileSharesState.DISABLED); } } return this; } @Override public StorageAccountImpl withHnsEnabled(boolean enabled) { this.createParameters.withIsHnsEnabled(enabled); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel; private PrivateLinkResourceImpl(com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.requiredZoneNames()); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
It is already in `StorageAccount`, so `ByStorageAccount` is kind of redundant. BTW, this name is from the shared interface.
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); }
.listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name())
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); }
class StorageAccountImpl extends GroupableResourceImpl<StorageAccount, StorageAccountInner, StorageAccountImpl, StorageManager> implements StorageAccount, StorageAccount.Definition, StorageAccount.Update { private final ClientLogger logger = new ClientLogger(getClass()); private PublicEndpoints publicEndpoints; private AccountStatuses accountStatuses; private StorageAccountCreateParameters createParameters; private StorageAccountUpdateParameters updateParameters; private StorageNetworkRulesHelper networkRulesHelper; private StorageEncryptionHelper encryptionHelper; StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager) { super(name, innerModel, storageManager); this.createParameters = new StorageAccountCreateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.createParameters); this.encryptionHelper = new StorageEncryptionHelper(this.createParameters); } @Override public AccountStatuses accountStatuses() { if (accountStatuses == null) { accountStatuses = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); } return accountStatuses; } @Override public StorageAccountSkuType skuType() { return StorageAccountSkuType.fromSkuName(this.innerModel().sku().name()); } @Override public Kind kind() { return innerModel().kind(); } @Override public OffsetDateTime creationTime() { return this.innerModel().creationTime(); } @Override public CustomDomain customDomain() { return this.innerModel().customDomain(); } @Override public OffsetDateTime lastGeoFailoverTime() { return this.innerModel().lastGeoFailoverTime(); } @Override public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } @Override public PublicEndpoints endPoints() { if (publicEndpoints == null) { publicEndpoints = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); } return publicEndpoints; } @Override public StorageAccountEncryptionKeySource encryptionKeySource() { return StorageEncryptionHelper.encryptionKeySource(this.innerModel()); } @Override public Map<StorageService, StorageAccountEncryptionStatus> encryptionStatuses() { return StorageEncryptionHelper.encryptionStatuses(this.innerModel()); } @Override public AccessTier accessTier() { return innerModel().accessTier(); } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().tenantId(); } } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().principalId(); } } @Override public boolean isAccessAllowedFromAllNetworks() { return StorageNetworkRulesHelper.isAccessAllowedFromAllNetworks(this.innerModel()); } @Override public List<String> networkSubnetsWithAccess() { return StorageNetworkRulesHelper.networkSubnetsWithAccess(this.innerModel()); } @Override public List<String> ipAddressesWithAccess() { return StorageNetworkRulesHelper.ipAddressesWithAccess(this.innerModel()); } @Override public List<String> ipAddressRangesWithAccess() { return StorageNetworkRulesHelper.ipAddressRangesWithAccess(this.innerModel()); } @Override public boolean canReadLogEntriesFromAnyNetwork() { return StorageNetworkRulesHelper.canReadLogEntriesFromAnyNetwork(this.innerModel()); } @Override public boolean canReadMetricsFromAnyNetwork() { return StorageNetworkRulesHelper.canReadMetricsFromAnyNetwork(this.innerModel()); } @Override public boolean canAccessFromAzureServices() { return StorageNetworkRulesHelper.canAccessFromAzureServices(this.innerModel()); } @Override public boolean isAzureFilesAadIntegrationEnabled() { return this.innerModel().azureFilesIdentityBasedAuthentication() != null && this.innerModel().azureFilesIdentityBasedAuthentication().directoryServiceOptions() == DirectoryServiceOptions.AADDS; } @Override public boolean isHnsEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().isHnsEnabled()); } @Override public boolean isLargeFileSharesEnabled() { return this.innerModel().largeFileSharesState() == LargeFileSharesState.ENABLED; } @Override public MinimumTlsVersion minimumTlsVersion() { return this.innerModel().minimumTlsVersion(); } @Override public boolean isHttpsTrafficOnly() { if (this.innerModel().enableHttpsTrafficOnly() == null) { return true; } return this.innerModel().enableHttpsTrafficOnly(); } @Override public boolean isBlobPublicAccessAllowed() { if (this.innerModel().allowBlobPublicAccess() == null) { return true; } return this.innerModel().allowBlobPublicAccess(); } @Override public boolean isSharedKeyAccessAllowed() { if (this.innerModel().allowSharedKeyAccess() == null) { return true; } return this.innerModel().allowSharedKeyAccess(); } @Override public List<StorageAccountKey> getKeys() { return this.getKeysAsync().block(); } @Override public Mono<List<StorageAccountKey>> getKeysAsync() { return this .manager() .serviceClient() .getStorageAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public List<StorageAccountKey> regenerateKey(String keyName) { return this.regenerateKeyAsync(keyName).block(); } @Override public Mono<List<StorageAccountKey>> regenerateKeyAsync(String keyName) { return this .manager() .serviceClient() .getStorageAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), keyName) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @Override public void approvePrivateEndpointConnection(String privateEndpointConnectionName) { approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new com.azure.resourcemanager.storage.models.PrivateLinkServiceConnectionState() .withStatus( com.azure.resourcemanager.storage.models.PrivateEndpointServiceConnectionStatus.APPROVED)) .then(); } @Override public Mono<StorageAccount> refreshAsync() { return super .refreshAsync() .map( storageAccount -> { StorageAccountImpl impl = (StorageAccountImpl) storageAccount; impl.clearWrapperProperties(); return impl; }); } @Override protected Mono<StorageAccountInner> getInnerAsync() { return this.manager().serviceClient().getStorageAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public StorageAccountImpl withSku(StorageAccountSkuType sku) { if (isInCreateMode()) { createParameters.withSku(new Sku().withName(sku.name())); } else { updateParameters.withSku(new Sku().withName(sku.name())); } return this; } @Override public StorageAccountImpl withBlobStorageAccountKind() { createParameters.withKind(Kind.BLOB_STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKind() { createParameters.withKind(Kind.STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKindV2() { createParameters.withKind(Kind.STORAGE_V2); return this; } @Override public StorageAccountImpl withBlockBlobStorageAccountKind() { createParameters.withKind(Kind.BLOCK_BLOB_STORAGE); return this; } @Override public StorageAccountImpl withFileStorageAccountKind() { createParameters.withKind(Kind.FILE_STORAGE); return this; } @Override public StorageAccountImpl withBlobEncryption() { this.encryptionHelper.withBlobEncryption(); return this; } @Override public StorageAccountImpl withFileEncryption() { this.encryptionHelper.withFileEncryption(); return this; } @Override public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion) { this.encryptionHelper.withEncryptionKeyFromKeyVault(keyVaultUri, keyName, keyVersion); return this; } @Override public StorageAccountImpl withoutBlobEncryption() { this.encryptionHelper.withoutBlobEncryption(); return this; } @Override public StorageAccountImpl withoutFileEncryption() { this.encryptionHelper.withoutFileEncryption(); return this; } private void clearWrapperProperties() { accountStatuses = null; publicEndpoints = null; } @Override public StorageAccountImpl update() { createParameters = null; updateParameters = new StorageAccountUpdateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.updateParameters, this.innerModel()); this.encryptionHelper = new StorageEncryptionHelper(this.updateParameters, this.innerModel()); return super.update(); } @Override public StorageAccountImpl withCustomDomain(CustomDomain customDomain) { if (isInCreateMode()) { createParameters.withCustomDomain(customDomain); } else { updateParameters.withCustomDomain(customDomain); } return this; } @Override public StorageAccountImpl withCustomDomain(String name) { return withCustomDomain(new CustomDomain().withName(name)); } @Override public StorageAccountImpl withCustomDomain(String name, boolean useSubDomain) { return withCustomDomain(new CustomDomain().withName(name).withUseSubDomainName(useSubDomain)); } @Override public StorageAccountImpl withAccessTier(AccessTier accessTier) { if (isInCreateMode()) { createParameters.withAccessTier(accessTier); } else { if (this.innerModel().kind() != Kind.BLOB_STORAGE) { throw logger.logExceptionAsError(new UnsupportedOperationException( "Access tier can not be changed for general purpose storage accounts.")); } updateParameters.withAccessTier(accessTier); } return this; } @Override public StorageAccountImpl withSystemAssignedManagedServiceIdentity() { if (this.innerModel().identity() == null) { if (isInCreateMode()) { createParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } else { updateParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } } return this; } @Override public StorageAccountImpl withOnlyHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(true); } else { updateParameters.withEnableHttpsTrafficOnly(true); } return this; } @Override public StorageAccountImpl withHttpAndHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(false); } else { updateParameters.withEnableHttpsTrafficOnly(false); } return this; } @Override public StorageAccountImpl withMinimumTlsVersion(MinimumTlsVersion minimumTlsVersion) { if (isInCreateMode()) { createParameters.withMinimumTlsVersion(minimumTlsVersion); } else { updateParameters.withMinimumTlsVersion(minimumTlsVersion); } return this; } @Override public StorageAccountImpl enableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(true); } else { updateParameters.withAllowBlobPublicAccess(true); } return this; } @Override public StorageAccountImpl disableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(false); } else { updateParameters.withAllowBlobPublicAccess(false); } return this; } @Override public StorageAccountImpl enableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(true); } else { updateParameters.withAllowSharedKeyAccess(true); } return this; } @Override public StorageAccountImpl disableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(false); } else { updateParameters.withAllowSharedKeyAccess(false); } return this; } @Override public StorageAccountImpl withAccessFromAllNetworks() { this.networkRulesHelper.withAccessFromAllNetworks(); return this; } @Override public StorageAccountImpl withAccessFromSelectedNetworks() { this.networkRulesHelper.withAccessFromSelectedNetworks(); return this; } @Override public StorageAccountImpl withAccessFromNetworkSubnet(String subnetId) { this.networkRulesHelper.withAccessFromNetworkSubnet(subnetId); return this; } @Override public StorageAccountImpl withAccessFromIpAddress(String ipAddress) { this.networkRulesHelper.withAccessFromIpAddress(ipAddress); return this; } @Override public StorageAccountImpl withAccessFromIpAddressRange(String ipAddressCidr) { this.networkRulesHelper.withAccessFromIpAddressRange(ipAddressCidr); return this; } @Override public StorageAccountImpl withReadAccessToLogEntriesFromAnyNetwork() { this.networkRulesHelper.withReadAccessToLoggingFromAnyNetwork(); return this; } @Override public StorageAccountImpl withReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withReadAccessToMetricsFromAnyNetwork(); return this; } @Override public StorageAccountImpl withAccessFromAzureServices() { this.networkRulesHelper.withAccessAllowedFromAzureServices(); return this; } @Override public StorageAccountImpl withoutNetworkSubnetAccess(String subnetId) { this.networkRulesHelper.withoutNetworkSubnetAccess(subnetId); return this; } @Override public StorageAccountImpl withoutIpAddressAccess(String ipAddress) { this.networkRulesHelper.withoutIpAddressAccess(ipAddress); return this; } @Override public StorageAccountImpl withoutIpAddressRangeAccess(String ipAddressCidr) { this.networkRulesHelper.withoutIpAddressRangeAccess(ipAddressCidr); return this; } @Override public Update withoutReadAccessToLoggingFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToLoggingFromAnyNetwork(); return this; } @Override public Update withoutReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToMetricsFromAnyNetwork(); return this; } @Override public Update withoutAccessFromAzureServices() { this.networkRulesHelper.withoutAccessFromAzureServices(); return this; } @Override public Update upgradeToGeneralPurposeAccountKindV2() { updateParameters.withKind(Kind.STORAGE_V2); return this; } @Override public Mono<StorageAccount> createResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); createParameters.withLocation(this.regionName()); createParameters.withTags(this.innerModel().tags()); final StorageAccountsClient client = this.manager().serviceClient().getStorageAccounts(); return this .manager() .serviceClient() .getStorageAccounts() .createAsync(this.resourceGroupName(), this.name(), createParameters) .flatMap( storageAccountInner -> client .getByResourceGroupAsync(resourceGroupName(), this.name()) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties())); } @Override public Mono<StorageAccount> updateResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); updateParameters.withTags(this.innerModel().tags()); return this .manager() .serviceClient() .getStorageAccounts() .updateAsync(resourceGroupName(), this.name(), updateParameters) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties()); } @Override public StorageAccountImpl withAzureFilesAadIntegrationEnabled(boolean enabled) { if (isInCreateMode()) { if (enabled) { this .createParameters .withAzureFilesIdentityBasedAuthentication( new AzureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); } } else { if (this.createParameters.azureFilesIdentityBasedAuthentication() == null) { this .createParameters .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication()); } if (enabled) { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS); } else { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.NONE); } } return this; } @Override public StorageAccountImpl withLargeFileShares(boolean enabled) { if (isInCreateMode()) { if (enabled) { this.createParameters.withLargeFileSharesState(LargeFileSharesState.ENABLED); } else { this.createParameters.withLargeFileSharesState(LargeFileSharesState.DISABLED); } } return this; } @Override public StorageAccountImpl withHnsEnabled(boolean enabled) { this.createParameters.withIsHnsEnabled(enabled); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel; private PrivateLinkResourceImpl(com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.requiredZoneNames()); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; public PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class StorageAccountImpl extends GroupableResourceImpl<StorageAccount, StorageAccountInner, StorageAccountImpl, StorageManager> implements StorageAccount, StorageAccount.Definition, StorageAccount.Update { private final ClientLogger logger = new ClientLogger(getClass()); private PublicEndpoints publicEndpoints; private AccountStatuses accountStatuses; private StorageAccountCreateParameters createParameters; private StorageAccountUpdateParameters updateParameters; private StorageNetworkRulesHelper networkRulesHelper; private StorageEncryptionHelper encryptionHelper; StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager) { super(name, innerModel, storageManager); this.createParameters = new StorageAccountCreateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.createParameters); this.encryptionHelper = new StorageEncryptionHelper(this.createParameters); } @Override public AccountStatuses accountStatuses() { if (accountStatuses == null) { accountStatuses = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); } return accountStatuses; } @Override public StorageAccountSkuType skuType() { return StorageAccountSkuType.fromSkuName(this.innerModel().sku().name()); } @Override public Kind kind() { return innerModel().kind(); } @Override public OffsetDateTime creationTime() { return this.innerModel().creationTime(); } @Override public CustomDomain customDomain() { return this.innerModel().customDomain(); } @Override public OffsetDateTime lastGeoFailoverTime() { return this.innerModel().lastGeoFailoverTime(); } @Override public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } @Override public PublicEndpoints endPoints() { if (publicEndpoints == null) { publicEndpoints = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); } return publicEndpoints; } @Override public StorageAccountEncryptionKeySource encryptionKeySource() { return StorageEncryptionHelper.encryptionKeySource(this.innerModel()); } @Override public Map<StorageService, StorageAccountEncryptionStatus> encryptionStatuses() { return StorageEncryptionHelper.encryptionStatuses(this.innerModel()); } @Override public AccessTier accessTier() { return innerModel().accessTier(); } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().tenantId(); } } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().principalId(); } } @Override public boolean isAccessAllowedFromAllNetworks() { return StorageNetworkRulesHelper.isAccessAllowedFromAllNetworks(this.innerModel()); } @Override public List<String> networkSubnetsWithAccess() { return StorageNetworkRulesHelper.networkSubnetsWithAccess(this.innerModel()); } @Override public List<String> ipAddressesWithAccess() { return StorageNetworkRulesHelper.ipAddressesWithAccess(this.innerModel()); } @Override public List<String> ipAddressRangesWithAccess() { return StorageNetworkRulesHelper.ipAddressRangesWithAccess(this.innerModel()); } @Override public boolean canReadLogEntriesFromAnyNetwork() { return StorageNetworkRulesHelper.canReadLogEntriesFromAnyNetwork(this.innerModel()); } @Override public boolean canReadMetricsFromAnyNetwork() { return StorageNetworkRulesHelper.canReadMetricsFromAnyNetwork(this.innerModel()); } @Override public boolean canAccessFromAzureServices() { return StorageNetworkRulesHelper.canAccessFromAzureServices(this.innerModel()); } @Override public boolean isAzureFilesAadIntegrationEnabled() { return this.innerModel().azureFilesIdentityBasedAuthentication() != null && this.innerModel().azureFilesIdentityBasedAuthentication().directoryServiceOptions() == DirectoryServiceOptions.AADDS; } @Override public boolean isHnsEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().isHnsEnabled()); } @Override public boolean isLargeFileSharesEnabled() { return this.innerModel().largeFileSharesState() == LargeFileSharesState.ENABLED; } @Override public MinimumTlsVersion minimumTlsVersion() { return this.innerModel().minimumTlsVersion(); } @Override public boolean isHttpsTrafficOnly() { if (this.innerModel().enableHttpsTrafficOnly() == null) { return true; } return this.innerModel().enableHttpsTrafficOnly(); } @Override public boolean isBlobPublicAccessAllowed() { if (this.innerModel().allowBlobPublicAccess() == null) { return true; } return this.innerModel().allowBlobPublicAccess(); } @Override public boolean isSharedKeyAccessAllowed() { if (this.innerModel().allowSharedKeyAccess() == null) { return true; } return this.innerModel().allowSharedKeyAccess(); } @Override public List<StorageAccountKey> getKeys() { return this.getKeysAsync().block(); } @Override public Mono<List<StorageAccountKey>> getKeysAsync() { return this .manager() .serviceClient() .getStorageAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public List<StorageAccountKey> regenerateKey(String keyName) { return this.regenerateKeyAsync(keyName).block(); } @Override public Mono<List<StorageAccountKey>> regenerateKeyAsync(String keyName) { return this .manager() .serviceClient() .getStorageAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), keyName) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @Override public void approvePrivateEndpointConnection(String privateEndpointConnectionName) { approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new com.azure.resourcemanager.storage.models.PrivateLinkServiceConnectionState() .withStatus( com.azure.resourcemanager.storage.models.PrivateEndpointServiceConnectionStatus.APPROVED)) .then(); } @Override public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) { rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new PrivateLinkServiceConnectionState() .withStatus( PrivateEndpointServiceConnectionStatus.REJECTED)) .then(); } @Override public Mono<StorageAccount> refreshAsync() { return super .refreshAsync() .map( storageAccount -> { StorageAccountImpl impl = (StorageAccountImpl) storageAccount; impl.clearWrapperProperties(); return impl; }); } @Override protected Mono<StorageAccountInner> getInnerAsync() { return this.manager().serviceClient().getStorageAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public StorageAccountImpl withSku(StorageAccountSkuType sku) { if (isInCreateMode()) { createParameters.withSku(new Sku().withName(sku.name())); } else { updateParameters.withSku(new Sku().withName(sku.name())); } return this; } @Override public StorageAccountImpl withBlobStorageAccountKind() { createParameters.withKind(Kind.BLOB_STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKind() { createParameters.withKind(Kind.STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKindV2() { createParameters.withKind(Kind.STORAGE_V2); return this; } @Override public StorageAccountImpl withBlockBlobStorageAccountKind() { createParameters.withKind(Kind.BLOCK_BLOB_STORAGE); return this; } @Override public StorageAccountImpl withFileStorageAccountKind() { createParameters.withKind(Kind.FILE_STORAGE); return this; } @Override public StorageAccountImpl withBlobEncryption() { this.encryptionHelper.withBlobEncryption(); return this; } @Override public StorageAccountImpl withFileEncryption() { this.encryptionHelper.withFileEncryption(); return this; } @Override public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion) { this.encryptionHelper.withEncryptionKeyFromKeyVault(keyVaultUri, keyName, keyVersion); return this; } @Override public StorageAccountImpl withoutBlobEncryption() { this.encryptionHelper.withoutBlobEncryption(); return this; } @Override public StorageAccountImpl withoutFileEncryption() { this.encryptionHelper.withoutFileEncryption(); return this; } private void clearWrapperProperties() { accountStatuses = null; publicEndpoints = null; } @Override public StorageAccountImpl update() { createParameters = null; updateParameters = new StorageAccountUpdateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.updateParameters, this.innerModel()); this.encryptionHelper = new StorageEncryptionHelper(this.updateParameters, this.innerModel()); return super.update(); } @Override public StorageAccountImpl withCustomDomain(CustomDomain customDomain) { if (isInCreateMode()) { createParameters.withCustomDomain(customDomain); } else { updateParameters.withCustomDomain(customDomain); } return this; } @Override public StorageAccountImpl withCustomDomain(String name) { return withCustomDomain(new CustomDomain().withName(name)); } @Override public StorageAccountImpl withCustomDomain(String name, boolean useSubDomain) { return withCustomDomain(new CustomDomain().withName(name).withUseSubDomainName(useSubDomain)); } @Override public StorageAccountImpl withAccessTier(AccessTier accessTier) { if (isInCreateMode()) { createParameters.withAccessTier(accessTier); } else { if (this.innerModel().kind() != Kind.BLOB_STORAGE) { throw logger.logExceptionAsError(new UnsupportedOperationException( "Access tier can not be changed for general purpose storage accounts.")); } updateParameters.withAccessTier(accessTier); } return this; } @Override public StorageAccountImpl withSystemAssignedManagedServiceIdentity() { if (this.innerModel().identity() == null) { if (isInCreateMode()) { createParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } else { updateParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } } return this; } @Override public StorageAccountImpl withOnlyHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(true); } else { updateParameters.withEnableHttpsTrafficOnly(true); } return this; } @Override public StorageAccountImpl withHttpAndHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(false); } else { updateParameters.withEnableHttpsTrafficOnly(false); } return this; } @Override public StorageAccountImpl withMinimumTlsVersion(MinimumTlsVersion minimumTlsVersion) { if (isInCreateMode()) { createParameters.withMinimumTlsVersion(minimumTlsVersion); } else { updateParameters.withMinimumTlsVersion(minimumTlsVersion); } return this; } @Override public StorageAccountImpl enableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(true); } else { updateParameters.withAllowBlobPublicAccess(true); } return this; } @Override public StorageAccountImpl disableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(false); } else { updateParameters.withAllowBlobPublicAccess(false); } return this; } @Override public StorageAccountImpl enableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(true); } else { updateParameters.withAllowSharedKeyAccess(true); } return this; } @Override public StorageAccountImpl disableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(false); } else { updateParameters.withAllowSharedKeyAccess(false); } return this; } @Override public StorageAccountImpl withAccessFromAllNetworks() { this.networkRulesHelper.withAccessFromAllNetworks(); return this; } @Override public StorageAccountImpl withAccessFromSelectedNetworks() { this.networkRulesHelper.withAccessFromSelectedNetworks(); return this; } @Override public StorageAccountImpl withAccessFromNetworkSubnet(String subnetId) { this.networkRulesHelper.withAccessFromNetworkSubnet(subnetId); return this; } @Override public StorageAccountImpl withAccessFromIpAddress(String ipAddress) { this.networkRulesHelper.withAccessFromIpAddress(ipAddress); return this; } @Override public StorageAccountImpl withAccessFromIpAddressRange(String ipAddressCidr) { this.networkRulesHelper.withAccessFromIpAddressRange(ipAddressCidr); return this; } @Override public StorageAccountImpl withReadAccessToLogEntriesFromAnyNetwork() { this.networkRulesHelper.withReadAccessToLoggingFromAnyNetwork(); return this; } @Override public StorageAccountImpl withReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withReadAccessToMetricsFromAnyNetwork(); return this; } @Override public StorageAccountImpl withAccessFromAzureServices() { this.networkRulesHelper.withAccessAllowedFromAzureServices(); return this; } @Override public StorageAccountImpl withoutNetworkSubnetAccess(String subnetId) { this.networkRulesHelper.withoutNetworkSubnetAccess(subnetId); return this; } @Override public StorageAccountImpl withoutIpAddressAccess(String ipAddress) { this.networkRulesHelper.withoutIpAddressAccess(ipAddress); return this; } @Override public StorageAccountImpl withoutIpAddressRangeAccess(String ipAddressCidr) { this.networkRulesHelper.withoutIpAddressRangeAccess(ipAddressCidr); return this; } @Override public Update withoutReadAccessToLoggingFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToLoggingFromAnyNetwork(); return this; } @Override public Update withoutReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToMetricsFromAnyNetwork(); return this; } @Override public Update withoutAccessFromAzureServices() { this.networkRulesHelper.withoutAccessFromAzureServices(); return this; } @Override public Update upgradeToGeneralPurposeAccountKindV2() { updateParameters.withKind(Kind.STORAGE_V2); return this; } @Override public Mono<StorageAccount> createResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); createParameters.withLocation(this.regionName()); createParameters.withTags(this.innerModel().tags()); final StorageAccountsClient client = this.manager().serviceClient().getStorageAccounts(); return this .manager() .serviceClient() .getStorageAccounts() .createAsync(this.resourceGroupName(), this.name(), createParameters) .flatMap( storageAccountInner -> client .getByResourceGroupAsync(resourceGroupName(), this.name()) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties())); } @Override public Mono<StorageAccount> updateResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); updateParameters.withTags(this.innerModel().tags()); return this .manager() .serviceClient() .getStorageAccounts() .updateAsync(resourceGroupName(), this.name(), updateParameters) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties()); } @Override public StorageAccountImpl withAzureFilesAadIntegrationEnabled(boolean enabled) { if (isInCreateMode()) { if (enabled) { this .createParameters .withAzureFilesIdentityBasedAuthentication( new AzureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); } } else { if (this.createParameters.azureFilesIdentityBasedAuthentication() == null) { this .createParameters .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication()); } if (enabled) { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS); } else { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.NONE); } } return this; } @Override public StorageAccountImpl withLargeFileShares(boolean enabled) { if (isInCreateMode()) { if (enabled) { this.createParameters.withLargeFileSharesState(LargeFileSharesState.ENABLED); } else { this.createParameters.withLargeFileSharesState(LargeFileSharesState.DISABLED); } } return this; } @Override public StorageAccountImpl withHnsEnabled(boolean enabled) { this.createParameters.withIsHnsEnabled(enabled); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel; private PrivateLinkResourceImpl(com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.requiredZoneNames()); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
My thought is that use a function that return `PagedFlux` rather than `Response`, in order not to `collect` first.
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); }
.listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name())
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); }
class StorageAccountImpl extends GroupableResourceImpl<StorageAccount, StorageAccountInner, StorageAccountImpl, StorageManager> implements StorageAccount, StorageAccount.Definition, StorageAccount.Update { private final ClientLogger logger = new ClientLogger(getClass()); private PublicEndpoints publicEndpoints; private AccountStatuses accountStatuses; private StorageAccountCreateParameters createParameters; private StorageAccountUpdateParameters updateParameters; private StorageNetworkRulesHelper networkRulesHelper; private StorageEncryptionHelper encryptionHelper; StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager) { super(name, innerModel, storageManager); this.createParameters = new StorageAccountCreateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.createParameters); this.encryptionHelper = new StorageEncryptionHelper(this.createParameters); } @Override public AccountStatuses accountStatuses() { if (accountStatuses == null) { accountStatuses = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); } return accountStatuses; } @Override public StorageAccountSkuType skuType() { return StorageAccountSkuType.fromSkuName(this.innerModel().sku().name()); } @Override public Kind kind() { return innerModel().kind(); } @Override public OffsetDateTime creationTime() { return this.innerModel().creationTime(); } @Override public CustomDomain customDomain() { return this.innerModel().customDomain(); } @Override public OffsetDateTime lastGeoFailoverTime() { return this.innerModel().lastGeoFailoverTime(); } @Override public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } @Override public PublicEndpoints endPoints() { if (publicEndpoints == null) { publicEndpoints = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); } return publicEndpoints; } @Override public StorageAccountEncryptionKeySource encryptionKeySource() { return StorageEncryptionHelper.encryptionKeySource(this.innerModel()); } @Override public Map<StorageService, StorageAccountEncryptionStatus> encryptionStatuses() { return StorageEncryptionHelper.encryptionStatuses(this.innerModel()); } @Override public AccessTier accessTier() { return innerModel().accessTier(); } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().tenantId(); } } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().principalId(); } } @Override public boolean isAccessAllowedFromAllNetworks() { return StorageNetworkRulesHelper.isAccessAllowedFromAllNetworks(this.innerModel()); } @Override public List<String> networkSubnetsWithAccess() { return StorageNetworkRulesHelper.networkSubnetsWithAccess(this.innerModel()); } @Override public List<String> ipAddressesWithAccess() { return StorageNetworkRulesHelper.ipAddressesWithAccess(this.innerModel()); } @Override public List<String> ipAddressRangesWithAccess() { return StorageNetworkRulesHelper.ipAddressRangesWithAccess(this.innerModel()); } @Override public boolean canReadLogEntriesFromAnyNetwork() { return StorageNetworkRulesHelper.canReadLogEntriesFromAnyNetwork(this.innerModel()); } @Override public boolean canReadMetricsFromAnyNetwork() { return StorageNetworkRulesHelper.canReadMetricsFromAnyNetwork(this.innerModel()); } @Override public boolean canAccessFromAzureServices() { return StorageNetworkRulesHelper.canAccessFromAzureServices(this.innerModel()); } @Override public boolean isAzureFilesAadIntegrationEnabled() { return this.innerModel().azureFilesIdentityBasedAuthentication() != null && this.innerModel().azureFilesIdentityBasedAuthentication().directoryServiceOptions() == DirectoryServiceOptions.AADDS; } @Override public boolean isHnsEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().isHnsEnabled()); } @Override public boolean isLargeFileSharesEnabled() { return this.innerModel().largeFileSharesState() == LargeFileSharesState.ENABLED; } @Override public MinimumTlsVersion minimumTlsVersion() { return this.innerModel().minimumTlsVersion(); } @Override public boolean isHttpsTrafficOnly() { if (this.innerModel().enableHttpsTrafficOnly() == null) { return true; } return this.innerModel().enableHttpsTrafficOnly(); } @Override public boolean isBlobPublicAccessAllowed() { if (this.innerModel().allowBlobPublicAccess() == null) { return true; } return this.innerModel().allowBlobPublicAccess(); } @Override public boolean isSharedKeyAccessAllowed() { if (this.innerModel().allowSharedKeyAccess() == null) { return true; } return this.innerModel().allowSharedKeyAccess(); } @Override public List<StorageAccountKey> getKeys() { return this.getKeysAsync().block(); } @Override public Mono<List<StorageAccountKey>> getKeysAsync() { return this .manager() .serviceClient() .getStorageAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public List<StorageAccountKey> regenerateKey(String keyName) { return this.regenerateKeyAsync(keyName).block(); } @Override public Mono<List<StorageAccountKey>> regenerateKeyAsync(String keyName) { return this .manager() .serviceClient() .getStorageAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), keyName) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @Override public void approvePrivateEndpointConnection(String privateEndpointConnectionName) { approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new com.azure.resourcemanager.storage.models.PrivateLinkServiceConnectionState() .withStatus( com.azure.resourcemanager.storage.models.PrivateEndpointServiceConnectionStatus.APPROVED)) .then(); } @Override public Mono<StorageAccount> refreshAsync() { return super .refreshAsync() .map( storageAccount -> { StorageAccountImpl impl = (StorageAccountImpl) storageAccount; impl.clearWrapperProperties(); return impl; }); } @Override protected Mono<StorageAccountInner> getInnerAsync() { return this.manager().serviceClient().getStorageAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public StorageAccountImpl withSku(StorageAccountSkuType sku) { if (isInCreateMode()) { createParameters.withSku(new Sku().withName(sku.name())); } else { updateParameters.withSku(new Sku().withName(sku.name())); } return this; } @Override public StorageAccountImpl withBlobStorageAccountKind() { createParameters.withKind(Kind.BLOB_STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKind() { createParameters.withKind(Kind.STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKindV2() { createParameters.withKind(Kind.STORAGE_V2); return this; } @Override public StorageAccountImpl withBlockBlobStorageAccountKind() { createParameters.withKind(Kind.BLOCK_BLOB_STORAGE); return this; } @Override public StorageAccountImpl withFileStorageAccountKind() { createParameters.withKind(Kind.FILE_STORAGE); return this; } @Override public StorageAccountImpl withBlobEncryption() { this.encryptionHelper.withBlobEncryption(); return this; } @Override public StorageAccountImpl withFileEncryption() { this.encryptionHelper.withFileEncryption(); return this; } @Override public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion) { this.encryptionHelper.withEncryptionKeyFromKeyVault(keyVaultUri, keyName, keyVersion); return this; } @Override public StorageAccountImpl withoutBlobEncryption() { this.encryptionHelper.withoutBlobEncryption(); return this; } @Override public StorageAccountImpl withoutFileEncryption() { this.encryptionHelper.withoutFileEncryption(); return this; } private void clearWrapperProperties() { accountStatuses = null; publicEndpoints = null; } @Override public StorageAccountImpl update() { createParameters = null; updateParameters = new StorageAccountUpdateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.updateParameters, this.innerModel()); this.encryptionHelper = new StorageEncryptionHelper(this.updateParameters, this.innerModel()); return super.update(); } @Override public StorageAccountImpl withCustomDomain(CustomDomain customDomain) { if (isInCreateMode()) { createParameters.withCustomDomain(customDomain); } else { updateParameters.withCustomDomain(customDomain); } return this; } @Override public StorageAccountImpl withCustomDomain(String name) { return withCustomDomain(new CustomDomain().withName(name)); } @Override public StorageAccountImpl withCustomDomain(String name, boolean useSubDomain) { return withCustomDomain(new CustomDomain().withName(name).withUseSubDomainName(useSubDomain)); } @Override public StorageAccountImpl withAccessTier(AccessTier accessTier) { if (isInCreateMode()) { createParameters.withAccessTier(accessTier); } else { if (this.innerModel().kind() != Kind.BLOB_STORAGE) { throw logger.logExceptionAsError(new UnsupportedOperationException( "Access tier can not be changed for general purpose storage accounts.")); } updateParameters.withAccessTier(accessTier); } return this; } @Override public StorageAccountImpl withSystemAssignedManagedServiceIdentity() { if (this.innerModel().identity() == null) { if (isInCreateMode()) { createParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } else { updateParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } } return this; } @Override public StorageAccountImpl withOnlyHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(true); } else { updateParameters.withEnableHttpsTrafficOnly(true); } return this; } @Override public StorageAccountImpl withHttpAndHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(false); } else { updateParameters.withEnableHttpsTrafficOnly(false); } return this; } @Override public StorageAccountImpl withMinimumTlsVersion(MinimumTlsVersion minimumTlsVersion) { if (isInCreateMode()) { createParameters.withMinimumTlsVersion(minimumTlsVersion); } else { updateParameters.withMinimumTlsVersion(minimumTlsVersion); } return this; } @Override public StorageAccountImpl enableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(true); } else { updateParameters.withAllowBlobPublicAccess(true); } return this; } @Override public StorageAccountImpl disableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(false); } else { updateParameters.withAllowBlobPublicAccess(false); } return this; } @Override public StorageAccountImpl enableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(true); } else { updateParameters.withAllowSharedKeyAccess(true); } return this; } @Override public StorageAccountImpl disableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(false); } else { updateParameters.withAllowSharedKeyAccess(false); } return this; } @Override public StorageAccountImpl withAccessFromAllNetworks() { this.networkRulesHelper.withAccessFromAllNetworks(); return this; } @Override public StorageAccountImpl withAccessFromSelectedNetworks() { this.networkRulesHelper.withAccessFromSelectedNetworks(); return this; } @Override public StorageAccountImpl withAccessFromNetworkSubnet(String subnetId) { this.networkRulesHelper.withAccessFromNetworkSubnet(subnetId); return this; } @Override public StorageAccountImpl withAccessFromIpAddress(String ipAddress) { this.networkRulesHelper.withAccessFromIpAddress(ipAddress); return this; } @Override public StorageAccountImpl withAccessFromIpAddressRange(String ipAddressCidr) { this.networkRulesHelper.withAccessFromIpAddressRange(ipAddressCidr); return this; } @Override public StorageAccountImpl withReadAccessToLogEntriesFromAnyNetwork() { this.networkRulesHelper.withReadAccessToLoggingFromAnyNetwork(); return this; } @Override public StorageAccountImpl withReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withReadAccessToMetricsFromAnyNetwork(); return this; } @Override public StorageAccountImpl withAccessFromAzureServices() { this.networkRulesHelper.withAccessAllowedFromAzureServices(); return this; } @Override public StorageAccountImpl withoutNetworkSubnetAccess(String subnetId) { this.networkRulesHelper.withoutNetworkSubnetAccess(subnetId); return this; } @Override public StorageAccountImpl withoutIpAddressAccess(String ipAddress) { this.networkRulesHelper.withoutIpAddressAccess(ipAddress); return this; } @Override public StorageAccountImpl withoutIpAddressRangeAccess(String ipAddressCidr) { this.networkRulesHelper.withoutIpAddressRangeAccess(ipAddressCidr); return this; } @Override public Update withoutReadAccessToLoggingFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToLoggingFromAnyNetwork(); return this; } @Override public Update withoutReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToMetricsFromAnyNetwork(); return this; } @Override public Update withoutAccessFromAzureServices() { this.networkRulesHelper.withoutAccessFromAzureServices(); return this; } @Override public Update upgradeToGeneralPurposeAccountKindV2() { updateParameters.withKind(Kind.STORAGE_V2); return this; } @Override public Mono<StorageAccount> createResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); createParameters.withLocation(this.regionName()); createParameters.withTags(this.innerModel().tags()); final StorageAccountsClient client = this.manager().serviceClient().getStorageAccounts(); return this .manager() .serviceClient() .getStorageAccounts() .createAsync(this.resourceGroupName(), this.name(), createParameters) .flatMap( storageAccountInner -> client .getByResourceGroupAsync(resourceGroupName(), this.name()) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties())); } @Override public Mono<StorageAccount> updateResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); updateParameters.withTags(this.innerModel().tags()); return this .manager() .serviceClient() .getStorageAccounts() .updateAsync(resourceGroupName(), this.name(), updateParameters) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties()); } @Override public StorageAccountImpl withAzureFilesAadIntegrationEnabled(boolean enabled) { if (isInCreateMode()) { if (enabled) { this .createParameters .withAzureFilesIdentityBasedAuthentication( new AzureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); } } else { if (this.createParameters.azureFilesIdentityBasedAuthentication() == null) { this .createParameters .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication()); } if (enabled) { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS); } else { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.NONE); } } return this; } @Override public StorageAccountImpl withLargeFileShares(boolean enabled) { if (isInCreateMode()) { if (enabled) { this.createParameters.withLargeFileSharesState(LargeFileSharesState.ENABLED); } else { this.createParameters.withLargeFileSharesState(LargeFileSharesState.DISABLED); } } return this; } @Override public StorageAccountImpl withHnsEnabled(boolean enabled) { this.createParameters.withIsHnsEnabled(enabled); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel; private PrivateLinkResourceImpl(com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.requiredZoneNames()); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; public PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class StorageAccountImpl extends GroupableResourceImpl<StorageAccount, StorageAccountInner, StorageAccountImpl, StorageManager> implements StorageAccount, StorageAccount.Definition, StorageAccount.Update { private final ClientLogger logger = new ClientLogger(getClass()); private PublicEndpoints publicEndpoints; private AccountStatuses accountStatuses; private StorageAccountCreateParameters createParameters; private StorageAccountUpdateParameters updateParameters; private StorageNetworkRulesHelper networkRulesHelper; private StorageEncryptionHelper encryptionHelper; StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager) { super(name, innerModel, storageManager); this.createParameters = new StorageAccountCreateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.createParameters); this.encryptionHelper = new StorageEncryptionHelper(this.createParameters); } @Override public AccountStatuses accountStatuses() { if (accountStatuses == null) { accountStatuses = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); } return accountStatuses; } @Override public StorageAccountSkuType skuType() { return StorageAccountSkuType.fromSkuName(this.innerModel().sku().name()); } @Override public Kind kind() { return innerModel().kind(); } @Override public OffsetDateTime creationTime() { return this.innerModel().creationTime(); } @Override public CustomDomain customDomain() { return this.innerModel().customDomain(); } @Override public OffsetDateTime lastGeoFailoverTime() { return this.innerModel().lastGeoFailoverTime(); } @Override public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } @Override public PublicEndpoints endPoints() { if (publicEndpoints == null) { publicEndpoints = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); } return publicEndpoints; } @Override public StorageAccountEncryptionKeySource encryptionKeySource() { return StorageEncryptionHelper.encryptionKeySource(this.innerModel()); } @Override public Map<StorageService, StorageAccountEncryptionStatus> encryptionStatuses() { return StorageEncryptionHelper.encryptionStatuses(this.innerModel()); } @Override public AccessTier accessTier() { return innerModel().accessTier(); } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().tenantId(); } } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().principalId(); } } @Override public boolean isAccessAllowedFromAllNetworks() { return StorageNetworkRulesHelper.isAccessAllowedFromAllNetworks(this.innerModel()); } @Override public List<String> networkSubnetsWithAccess() { return StorageNetworkRulesHelper.networkSubnetsWithAccess(this.innerModel()); } @Override public List<String> ipAddressesWithAccess() { return StorageNetworkRulesHelper.ipAddressesWithAccess(this.innerModel()); } @Override public List<String> ipAddressRangesWithAccess() { return StorageNetworkRulesHelper.ipAddressRangesWithAccess(this.innerModel()); } @Override public boolean canReadLogEntriesFromAnyNetwork() { return StorageNetworkRulesHelper.canReadLogEntriesFromAnyNetwork(this.innerModel()); } @Override public boolean canReadMetricsFromAnyNetwork() { return StorageNetworkRulesHelper.canReadMetricsFromAnyNetwork(this.innerModel()); } @Override public boolean canAccessFromAzureServices() { return StorageNetworkRulesHelper.canAccessFromAzureServices(this.innerModel()); } @Override public boolean isAzureFilesAadIntegrationEnabled() { return this.innerModel().azureFilesIdentityBasedAuthentication() != null && this.innerModel().azureFilesIdentityBasedAuthentication().directoryServiceOptions() == DirectoryServiceOptions.AADDS; } @Override public boolean isHnsEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().isHnsEnabled()); } @Override public boolean isLargeFileSharesEnabled() { return this.innerModel().largeFileSharesState() == LargeFileSharesState.ENABLED; } @Override public MinimumTlsVersion minimumTlsVersion() { return this.innerModel().minimumTlsVersion(); } @Override public boolean isHttpsTrafficOnly() { if (this.innerModel().enableHttpsTrafficOnly() == null) { return true; } return this.innerModel().enableHttpsTrafficOnly(); } @Override public boolean isBlobPublicAccessAllowed() { if (this.innerModel().allowBlobPublicAccess() == null) { return true; } return this.innerModel().allowBlobPublicAccess(); } @Override public boolean isSharedKeyAccessAllowed() { if (this.innerModel().allowSharedKeyAccess() == null) { return true; } return this.innerModel().allowSharedKeyAccess(); } @Override public List<StorageAccountKey> getKeys() { return this.getKeysAsync().block(); } @Override public Mono<List<StorageAccountKey>> getKeysAsync() { return this .manager() .serviceClient() .getStorageAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public List<StorageAccountKey> regenerateKey(String keyName) { return this.regenerateKeyAsync(keyName).block(); } @Override public Mono<List<StorageAccountKey>> regenerateKeyAsync(String keyName) { return this .manager() .serviceClient() .getStorageAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), keyName) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @Override public void approvePrivateEndpointConnection(String privateEndpointConnectionName) { approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new com.azure.resourcemanager.storage.models.PrivateLinkServiceConnectionState() .withStatus( com.azure.resourcemanager.storage.models.PrivateEndpointServiceConnectionStatus.APPROVED)) .then(); } @Override public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) { rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new PrivateLinkServiceConnectionState() .withStatus( PrivateEndpointServiceConnectionStatus.REJECTED)) .then(); } @Override public Mono<StorageAccount> refreshAsync() { return super .refreshAsync() .map( storageAccount -> { StorageAccountImpl impl = (StorageAccountImpl) storageAccount; impl.clearWrapperProperties(); return impl; }); } @Override protected Mono<StorageAccountInner> getInnerAsync() { return this.manager().serviceClient().getStorageAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public StorageAccountImpl withSku(StorageAccountSkuType sku) { if (isInCreateMode()) { createParameters.withSku(new Sku().withName(sku.name())); } else { updateParameters.withSku(new Sku().withName(sku.name())); } return this; } @Override public StorageAccountImpl withBlobStorageAccountKind() { createParameters.withKind(Kind.BLOB_STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKind() { createParameters.withKind(Kind.STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKindV2() { createParameters.withKind(Kind.STORAGE_V2); return this; } @Override public StorageAccountImpl withBlockBlobStorageAccountKind() { createParameters.withKind(Kind.BLOCK_BLOB_STORAGE); return this; } @Override public StorageAccountImpl withFileStorageAccountKind() { createParameters.withKind(Kind.FILE_STORAGE); return this; } @Override public StorageAccountImpl withBlobEncryption() { this.encryptionHelper.withBlobEncryption(); return this; } @Override public StorageAccountImpl withFileEncryption() { this.encryptionHelper.withFileEncryption(); return this; } @Override public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion) { this.encryptionHelper.withEncryptionKeyFromKeyVault(keyVaultUri, keyName, keyVersion); return this; } @Override public StorageAccountImpl withoutBlobEncryption() { this.encryptionHelper.withoutBlobEncryption(); return this; } @Override public StorageAccountImpl withoutFileEncryption() { this.encryptionHelper.withoutFileEncryption(); return this; } private void clearWrapperProperties() { accountStatuses = null; publicEndpoints = null; } @Override public StorageAccountImpl update() { createParameters = null; updateParameters = new StorageAccountUpdateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.updateParameters, this.innerModel()); this.encryptionHelper = new StorageEncryptionHelper(this.updateParameters, this.innerModel()); return super.update(); } @Override public StorageAccountImpl withCustomDomain(CustomDomain customDomain) { if (isInCreateMode()) { createParameters.withCustomDomain(customDomain); } else { updateParameters.withCustomDomain(customDomain); } return this; } @Override public StorageAccountImpl withCustomDomain(String name) { return withCustomDomain(new CustomDomain().withName(name)); } @Override public StorageAccountImpl withCustomDomain(String name, boolean useSubDomain) { return withCustomDomain(new CustomDomain().withName(name).withUseSubDomainName(useSubDomain)); } @Override public StorageAccountImpl withAccessTier(AccessTier accessTier) { if (isInCreateMode()) { createParameters.withAccessTier(accessTier); } else { if (this.innerModel().kind() != Kind.BLOB_STORAGE) { throw logger.logExceptionAsError(new UnsupportedOperationException( "Access tier can not be changed for general purpose storage accounts.")); } updateParameters.withAccessTier(accessTier); } return this; } @Override public StorageAccountImpl withSystemAssignedManagedServiceIdentity() { if (this.innerModel().identity() == null) { if (isInCreateMode()) { createParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } else { updateParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } } return this; } @Override public StorageAccountImpl withOnlyHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(true); } else { updateParameters.withEnableHttpsTrafficOnly(true); } return this; } @Override public StorageAccountImpl withHttpAndHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(false); } else { updateParameters.withEnableHttpsTrafficOnly(false); } return this; } @Override public StorageAccountImpl withMinimumTlsVersion(MinimumTlsVersion minimumTlsVersion) { if (isInCreateMode()) { createParameters.withMinimumTlsVersion(minimumTlsVersion); } else { updateParameters.withMinimumTlsVersion(minimumTlsVersion); } return this; } @Override public StorageAccountImpl enableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(true); } else { updateParameters.withAllowBlobPublicAccess(true); } return this; } @Override public StorageAccountImpl disableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(false); } else { updateParameters.withAllowBlobPublicAccess(false); } return this; } @Override public StorageAccountImpl enableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(true); } else { updateParameters.withAllowSharedKeyAccess(true); } return this; } @Override public StorageAccountImpl disableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(false); } else { updateParameters.withAllowSharedKeyAccess(false); } return this; } @Override public StorageAccountImpl withAccessFromAllNetworks() { this.networkRulesHelper.withAccessFromAllNetworks(); return this; } @Override public StorageAccountImpl withAccessFromSelectedNetworks() { this.networkRulesHelper.withAccessFromSelectedNetworks(); return this; } @Override public StorageAccountImpl withAccessFromNetworkSubnet(String subnetId) { this.networkRulesHelper.withAccessFromNetworkSubnet(subnetId); return this; } @Override public StorageAccountImpl withAccessFromIpAddress(String ipAddress) { this.networkRulesHelper.withAccessFromIpAddress(ipAddress); return this; } @Override public StorageAccountImpl withAccessFromIpAddressRange(String ipAddressCidr) { this.networkRulesHelper.withAccessFromIpAddressRange(ipAddressCidr); return this; } @Override public StorageAccountImpl withReadAccessToLogEntriesFromAnyNetwork() { this.networkRulesHelper.withReadAccessToLoggingFromAnyNetwork(); return this; } @Override public StorageAccountImpl withReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withReadAccessToMetricsFromAnyNetwork(); return this; } @Override public StorageAccountImpl withAccessFromAzureServices() { this.networkRulesHelper.withAccessAllowedFromAzureServices(); return this; } @Override public StorageAccountImpl withoutNetworkSubnetAccess(String subnetId) { this.networkRulesHelper.withoutNetworkSubnetAccess(subnetId); return this; } @Override public StorageAccountImpl withoutIpAddressAccess(String ipAddress) { this.networkRulesHelper.withoutIpAddressAccess(ipAddress); return this; } @Override public StorageAccountImpl withoutIpAddressRangeAccess(String ipAddressCidr) { this.networkRulesHelper.withoutIpAddressRangeAccess(ipAddressCidr); return this; } @Override public Update withoutReadAccessToLoggingFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToLoggingFromAnyNetwork(); return this; } @Override public Update withoutReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToMetricsFromAnyNetwork(); return this; } @Override public Update withoutAccessFromAzureServices() { this.networkRulesHelper.withoutAccessFromAzureServices(); return this; } @Override public Update upgradeToGeneralPurposeAccountKindV2() { updateParameters.withKind(Kind.STORAGE_V2); return this; } @Override public Mono<StorageAccount> createResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); createParameters.withLocation(this.regionName()); createParameters.withTags(this.innerModel().tags()); final StorageAccountsClient client = this.manager().serviceClient().getStorageAccounts(); return this .manager() .serviceClient() .getStorageAccounts() .createAsync(this.resourceGroupName(), this.name(), createParameters) .flatMap( storageAccountInner -> client .getByResourceGroupAsync(resourceGroupName(), this.name()) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties())); } @Override public Mono<StorageAccount> updateResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); updateParameters.withTags(this.innerModel().tags()); return this .manager() .serviceClient() .getStorageAccounts() .updateAsync(resourceGroupName(), this.name(), updateParameters) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties()); } @Override public StorageAccountImpl withAzureFilesAadIntegrationEnabled(boolean enabled) { if (isInCreateMode()) { if (enabled) { this .createParameters .withAzureFilesIdentityBasedAuthentication( new AzureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); } } else { if (this.createParameters.azureFilesIdentityBasedAuthentication() == null) { this .createParameters .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication()); } if (enabled) { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS); } else { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.NONE); } } return this; } @Override public StorageAccountImpl withLargeFileShares(boolean enabled) { if (isInCreateMode()) { if (enabled) { this.createParameters.withLargeFileSharesState(LargeFileSharesState.ENABLED); } else { this.createParameters.withLargeFileSharesState(LargeFileSharesState.DISABLED); } } return this; } @Override public StorageAccountImpl withHnsEnabled(boolean enabled) { this.createParameters.withIsHnsEnabled(enabled); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel; private PrivateLinkResourceImpl(com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.requiredZoneNames()); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
Currently the spec API is not a paging one, but it actually return not a `List`, but a response with `values` as List (which is same as a paged operation). Hence the manual transform of that response to a `PagedFlux`. As `PagedFlux` contains header/code info, hence the `Response`.
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); }
.listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name())
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listByStorageAccountWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); }
class StorageAccountImpl extends GroupableResourceImpl<StorageAccount, StorageAccountInner, StorageAccountImpl, StorageManager> implements StorageAccount, StorageAccount.Definition, StorageAccount.Update { private final ClientLogger logger = new ClientLogger(getClass()); private PublicEndpoints publicEndpoints; private AccountStatuses accountStatuses; private StorageAccountCreateParameters createParameters; private StorageAccountUpdateParameters updateParameters; private StorageNetworkRulesHelper networkRulesHelper; private StorageEncryptionHelper encryptionHelper; StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager) { super(name, innerModel, storageManager); this.createParameters = new StorageAccountCreateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.createParameters); this.encryptionHelper = new StorageEncryptionHelper(this.createParameters); } @Override public AccountStatuses accountStatuses() { if (accountStatuses == null) { accountStatuses = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); } return accountStatuses; } @Override public StorageAccountSkuType skuType() { return StorageAccountSkuType.fromSkuName(this.innerModel().sku().name()); } @Override public Kind kind() { return innerModel().kind(); } @Override public OffsetDateTime creationTime() { return this.innerModel().creationTime(); } @Override public CustomDomain customDomain() { return this.innerModel().customDomain(); } @Override public OffsetDateTime lastGeoFailoverTime() { return this.innerModel().lastGeoFailoverTime(); } @Override public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } @Override public PublicEndpoints endPoints() { if (publicEndpoints == null) { publicEndpoints = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); } return publicEndpoints; } @Override public StorageAccountEncryptionKeySource encryptionKeySource() { return StorageEncryptionHelper.encryptionKeySource(this.innerModel()); } @Override public Map<StorageService, StorageAccountEncryptionStatus> encryptionStatuses() { return StorageEncryptionHelper.encryptionStatuses(this.innerModel()); } @Override public AccessTier accessTier() { return innerModel().accessTier(); } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().tenantId(); } } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().principalId(); } } @Override public boolean isAccessAllowedFromAllNetworks() { return StorageNetworkRulesHelper.isAccessAllowedFromAllNetworks(this.innerModel()); } @Override public List<String> networkSubnetsWithAccess() { return StorageNetworkRulesHelper.networkSubnetsWithAccess(this.innerModel()); } @Override public List<String> ipAddressesWithAccess() { return StorageNetworkRulesHelper.ipAddressesWithAccess(this.innerModel()); } @Override public List<String> ipAddressRangesWithAccess() { return StorageNetworkRulesHelper.ipAddressRangesWithAccess(this.innerModel()); } @Override public boolean canReadLogEntriesFromAnyNetwork() { return StorageNetworkRulesHelper.canReadLogEntriesFromAnyNetwork(this.innerModel()); } @Override public boolean canReadMetricsFromAnyNetwork() { return StorageNetworkRulesHelper.canReadMetricsFromAnyNetwork(this.innerModel()); } @Override public boolean canAccessFromAzureServices() { return StorageNetworkRulesHelper.canAccessFromAzureServices(this.innerModel()); } @Override public boolean isAzureFilesAadIntegrationEnabled() { return this.innerModel().azureFilesIdentityBasedAuthentication() != null && this.innerModel().azureFilesIdentityBasedAuthentication().directoryServiceOptions() == DirectoryServiceOptions.AADDS; } @Override public boolean isHnsEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().isHnsEnabled()); } @Override public boolean isLargeFileSharesEnabled() { return this.innerModel().largeFileSharesState() == LargeFileSharesState.ENABLED; } @Override public MinimumTlsVersion minimumTlsVersion() { return this.innerModel().minimumTlsVersion(); } @Override public boolean isHttpsTrafficOnly() { if (this.innerModel().enableHttpsTrafficOnly() == null) { return true; } return this.innerModel().enableHttpsTrafficOnly(); } @Override public boolean isBlobPublicAccessAllowed() { if (this.innerModel().allowBlobPublicAccess() == null) { return true; } return this.innerModel().allowBlobPublicAccess(); } @Override public boolean isSharedKeyAccessAllowed() { if (this.innerModel().allowSharedKeyAccess() == null) { return true; } return this.innerModel().allowSharedKeyAccess(); } @Override public List<StorageAccountKey> getKeys() { return this.getKeysAsync().block(); } @Override public Mono<List<StorageAccountKey>> getKeysAsync() { return this .manager() .serviceClient() .getStorageAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public List<StorageAccountKey> regenerateKey(String keyName) { return this.regenerateKeyAsync(keyName).block(); } @Override public Mono<List<StorageAccountKey>> regenerateKeyAsync(String keyName) { return this .manager() .serviceClient() .getStorageAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), keyName) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @Override public void approvePrivateEndpointConnection(String privateEndpointConnectionName) { approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new com.azure.resourcemanager.storage.models.PrivateLinkServiceConnectionState() .withStatus( com.azure.resourcemanager.storage.models.PrivateEndpointServiceConnectionStatus.APPROVED)) .then(); } @Override public Mono<StorageAccount> refreshAsync() { return super .refreshAsync() .map( storageAccount -> { StorageAccountImpl impl = (StorageAccountImpl) storageAccount; impl.clearWrapperProperties(); return impl; }); } @Override protected Mono<StorageAccountInner> getInnerAsync() { return this.manager().serviceClient().getStorageAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public StorageAccountImpl withSku(StorageAccountSkuType sku) { if (isInCreateMode()) { createParameters.withSku(new Sku().withName(sku.name())); } else { updateParameters.withSku(new Sku().withName(sku.name())); } return this; } @Override public StorageAccountImpl withBlobStorageAccountKind() { createParameters.withKind(Kind.BLOB_STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKind() { createParameters.withKind(Kind.STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKindV2() { createParameters.withKind(Kind.STORAGE_V2); return this; } @Override public StorageAccountImpl withBlockBlobStorageAccountKind() { createParameters.withKind(Kind.BLOCK_BLOB_STORAGE); return this; } @Override public StorageAccountImpl withFileStorageAccountKind() { createParameters.withKind(Kind.FILE_STORAGE); return this; } @Override public StorageAccountImpl withBlobEncryption() { this.encryptionHelper.withBlobEncryption(); return this; } @Override public StorageAccountImpl withFileEncryption() { this.encryptionHelper.withFileEncryption(); return this; } @Override public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion) { this.encryptionHelper.withEncryptionKeyFromKeyVault(keyVaultUri, keyName, keyVersion); return this; } @Override public StorageAccountImpl withoutBlobEncryption() { this.encryptionHelper.withoutBlobEncryption(); return this; } @Override public StorageAccountImpl withoutFileEncryption() { this.encryptionHelper.withoutFileEncryption(); return this; } private void clearWrapperProperties() { accountStatuses = null; publicEndpoints = null; } @Override public StorageAccountImpl update() { createParameters = null; updateParameters = new StorageAccountUpdateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.updateParameters, this.innerModel()); this.encryptionHelper = new StorageEncryptionHelper(this.updateParameters, this.innerModel()); return super.update(); } @Override public StorageAccountImpl withCustomDomain(CustomDomain customDomain) { if (isInCreateMode()) { createParameters.withCustomDomain(customDomain); } else { updateParameters.withCustomDomain(customDomain); } return this; } @Override public StorageAccountImpl withCustomDomain(String name) { return withCustomDomain(new CustomDomain().withName(name)); } @Override public StorageAccountImpl withCustomDomain(String name, boolean useSubDomain) { return withCustomDomain(new CustomDomain().withName(name).withUseSubDomainName(useSubDomain)); } @Override public StorageAccountImpl withAccessTier(AccessTier accessTier) { if (isInCreateMode()) { createParameters.withAccessTier(accessTier); } else { if (this.innerModel().kind() != Kind.BLOB_STORAGE) { throw logger.logExceptionAsError(new UnsupportedOperationException( "Access tier can not be changed for general purpose storage accounts.")); } updateParameters.withAccessTier(accessTier); } return this; } @Override public StorageAccountImpl withSystemAssignedManagedServiceIdentity() { if (this.innerModel().identity() == null) { if (isInCreateMode()) { createParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } else { updateParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } } return this; } @Override public StorageAccountImpl withOnlyHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(true); } else { updateParameters.withEnableHttpsTrafficOnly(true); } return this; } @Override public StorageAccountImpl withHttpAndHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(false); } else { updateParameters.withEnableHttpsTrafficOnly(false); } return this; } @Override public StorageAccountImpl withMinimumTlsVersion(MinimumTlsVersion minimumTlsVersion) { if (isInCreateMode()) { createParameters.withMinimumTlsVersion(minimumTlsVersion); } else { updateParameters.withMinimumTlsVersion(minimumTlsVersion); } return this; } @Override public StorageAccountImpl enableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(true); } else { updateParameters.withAllowBlobPublicAccess(true); } return this; } @Override public StorageAccountImpl disableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(false); } else { updateParameters.withAllowBlobPublicAccess(false); } return this; } @Override public StorageAccountImpl enableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(true); } else { updateParameters.withAllowSharedKeyAccess(true); } return this; } @Override public StorageAccountImpl disableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(false); } else { updateParameters.withAllowSharedKeyAccess(false); } return this; } @Override public StorageAccountImpl withAccessFromAllNetworks() { this.networkRulesHelper.withAccessFromAllNetworks(); return this; } @Override public StorageAccountImpl withAccessFromSelectedNetworks() { this.networkRulesHelper.withAccessFromSelectedNetworks(); return this; } @Override public StorageAccountImpl withAccessFromNetworkSubnet(String subnetId) { this.networkRulesHelper.withAccessFromNetworkSubnet(subnetId); return this; } @Override public StorageAccountImpl withAccessFromIpAddress(String ipAddress) { this.networkRulesHelper.withAccessFromIpAddress(ipAddress); return this; } @Override public StorageAccountImpl withAccessFromIpAddressRange(String ipAddressCidr) { this.networkRulesHelper.withAccessFromIpAddressRange(ipAddressCidr); return this; } @Override public StorageAccountImpl withReadAccessToLogEntriesFromAnyNetwork() { this.networkRulesHelper.withReadAccessToLoggingFromAnyNetwork(); return this; } @Override public StorageAccountImpl withReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withReadAccessToMetricsFromAnyNetwork(); return this; } @Override public StorageAccountImpl withAccessFromAzureServices() { this.networkRulesHelper.withAccessAllowedFromAzureServices(); return this; } @Override public StorageAccountImpl withoutNetworkSubnetAccess(String subnetId) { this.networkRulesHelper.withoutNetworkSubnetAccess(subnetId); return this; } @Override public StorageAccountImpl withoutIpAddressAccess(String ipAddress) { this.networkRulesHelper.withoutIpAddressAccess(ipAddress); return this; } @Override public StorageAccountImpl withoutIpAddressRangeAccess(String ipAddressCidr) { this.networkRulesHelper.withoutIpAddressRangeAccess(ipAddressCidr); return this; } @Override public Update withoutReadAccessToLoggingFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToLoggingFromAnyNetwork(); return this; } @Override public Update withoutReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToMetricsFromAnyNetwork(); return this; } @Override public Update withoutAccessFromAzureServices() { this.networkRulesHelper.withoutAccessFromAzureServices(); return this; } @Override public Update upgradeToGeneralPurposeAccountKindV2() { updateParameters.withKind(Kind.STORAGE_V2); return this; } @Override public Mono<StorageAccount> createResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); createParameters.withLocation(this.regionName()); createParameters.withTags(this.innerModel().tags()); final StorageAccountsClient client = this.manager().serviceClient().getStorageAccounts(); return this .manager() .serviceClient() .getStorageAccounts() .createAsync(this.resourceGroupName(), this.name(), createParameters) .flatMap( storageAccountInner -> client .getByResourceGroupAsync(resourceGroupName(), this.name()) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties())); } @Override public Mono<StorageAccount> updateResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); updateParameters.withTags(this.innerModel().tags()); return this .manager() .serviceClient() .getStorageAccounts() .updateAsync(resourceGroupName(), this.name(), updateParameters) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties()); } @Override public StorageAccountImpl withAzureFilesAadIntegrationEnabled(boolean enabled) { if (isInCreateMode()) { if (enabled) { this .createParameters .withAzureFilesIdentityBasedAuthentication( new AzureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); } } else { if (this.createParameters.azureFilesIdentityBasedAuthentication() == null) { this .createParameters .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication()); } if (enabled) { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS); } else { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.NONE); } } return this; } @Override public StorageAccountImpl withLargeFileShares(boolean enabled) { if (isInCreateMode()) { if (enabled) { this.createParameters.withLargeFileSharesState(LargeFileSharesState.ENABLED); } else { this.createParameters.withLargeFileSharesState(LargeFileSharesState.DISABLED); } } return this; } @Override public StorageAccountImpl withHnsEnabled(boolean enabled) { this.createParameters.withIsHnsEnabled(enabled); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel; private PrivateLinkResourceImpl(com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.requiredZoneNames()); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; public PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class StorageAccountImpl extends GroupableResourceImpl<StorageAccount, StorageAccountInner, StorageAccountImpl, StorageManager> implements StorageAccount, StorageAccount.Definition, StorageAccount.Update { private final ClientLogger logger = new ClientLogger(getClass()); private PublicEndpoints publicEndpoints; private AccountStatuses accountStatuses; private StorageAccountCreateParameters createParameters; private StorageAccountUpdateParameters updateParameters; private StorageNetworkRulesHelper networkRulesHelper; private StorageEncryptionHelper encryptionHelper; StorageAccountImpl(String name, StorageAccountInner innerModel, final StorageManager storageManager) { super(name, innerModel, storageManager); this.createParameters = new StorageAccountCreateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.createParameters); this.encryptionHelper = new StorageEncryptionHelper(this.createParameters); } @Override public AccountStatuses accountStatuses() { if (accountStatuses == null) { accountStatuses = new AccountStatuses(this.innerModel().statusOfPrimary(), this.innerModel().statusOfSecondary()); } return accountStatuses; } @Override public StorageAccountSkuType skuType() { return StorageAccountSkuType.fromSkuName(this.innerModel().sku().name()); } @Override public Kind kind() { return innerModel().kind(); } @Override public OffsetDateTime creationTime() { return this.innerModel().creationTime(); } @Override public CustomDomain customDomain() { return this.innerModel().customDomain(); } @Override public OffsetDateTime lastGeoFailoverTime() { return this.innerModel().lastGeoFailoverTime(); } @Override public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } @Override public PublicEndpoints endPoints() { if (publicEndpoints == null) { publicEndpoints = new PublicEndpoints(this.innerModel().primaryEndpoints(), this.innerModel().secondaryEndpoints()); } return publicEndpoints; } @Override public StorageAccountEncryptionKeySource encryptionKeySource() { return StorageEncryptionHelper.encryptionKeySource(this.innerModel()); } @Override public Map<StorageService, StorageAccountEncryptionStatus> encryptionStatuses() { return StorageEncryptionHelper.encryptionStatuses(this.innerModel()); } @Override public AccessTier accessTier() { return innerModel().accessTier(); } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().tenantId(); } } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (this.innerModel().identity() == null) { return null; } else { return this.innerModel().identity().principalId(); } } @Override public boolean isAccessAllowedFromAllNetworks() { return StorageNetworkRulesHelper.isAccessAllowedFromAllNetworks(this.innerModel()); } @Override public List<String> networkSubnetsWithAccess() { return StorageNetworkRulesHelper.networkSubnetsWithAccess(this.innerModel()); } @Override public List<String> ipAddressesWithAccess() { return StorageNetworkRulesHelper.ipAddressesWithAccess(this.innerModel()); } @Override public List<String> ipAddressRangesWithAccess() { return StorageNetworkRulesHelper.ipAddressRangesWithAccess(this.innerModel()); } @Override public boolean canReadLogEntriesFromAnyNetwork() { return StorageNetworkRulesHelper.canReadLogEntriesFromAnyNetwork(this.innerModel()); } @Override public boolean canReadMetricsFromAnyNetwork() { return StorageNetworkRulesHelper.canReadMetricsFromAnyNetwork(this.innerModel()); } @Override public boolean canAccessFromAzureServices() { return StorageNetworkRulesHelper.canAccessFromAzureServices(this.innerModel()); } @Override public boolean isAzureFilesAadIntegrationEnabled() { return this.innerModel().azureFilesIdentityBasedAuthentication() != null && this.innerModel().azureFilesIdentityBasedAuthentication().directoryServiceOptions() == DirectoryServiceOptions.AADDS; } @Override public boolean isHnsEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().isHnsEnabled()); } @Override public boolean isLargeFileSharesEnabled() { return this.innerModel().largeFileSharesState() == LargeFileSharesState.ENABLED; } @Override public MinimumTlsVersion minimumTlsVersion() { return this.innerModel().minimumTlsVersion(); } @Override public boolean isHttpsTrafficOnly() { if (this.innerModel().enableHttpsTrafficOnly() == null) { return true; } return this.innerModel().enableHttpsTrafficOnly(); } @Override public boolean isBlobPublicAccessAllowed() { if (this.innerModel().allowBlobPublicAccess() == null) { return true; } return this.innerModel().allowBlobPublicAccess(); } @Override public boolean isSharedKeyAccessAllowed() { if (this.innerModel().allowSharedKeyAccess() == null) { return true; } return this.innerModel().allowSharedKeyAccess(); } @Override public List<StorageAccountKey> getKeys() { return this.getKeysAsync().block(); } @Override public Mono<List<StorageAccountKey>> getKeysAsync() { return this .manager() .serviceClient() .getStorageAccounts() .listKeysAsync(this.resourceGroupName(), this.name()) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public List<StorageAccountKey> regenerateKey(String keyName) { return this.regenerateKeyAsync(keyName).block(); } @Override public Mono<List<StorageAccountKey>> regenerateKeyAsync(String keyName) { return this .manager() .serviceClient() .getStorageAccounts() .regenerateKeyAsync(this.resourceGroupName(), this.name(), keyName) .map(storageAccountListKeysResultInner -> storageAccountListKeysResultInner.keys()); } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { return PagedConverter.mapPage(this.manager().serviceClient().getPrivateEndpointConnections() .listAsync(this.resourceGroupName(), this.name()), PrivateEndpointConnectionImpl::new); } @Override public void approvePrivateEndpointConnection(String privateEndpointConnectionName) { approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new com.azure.resourcemanager.storage.models.PrivateLinkServiceConnectionState() .withStatus( com.azure.resourcemanager.storage.models.PrivateEndpointServiceConnectionStatus.APPROVED)) .then(); } @Override public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) { rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block(); } @Override public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) { return this.manager().serviceClient().getPrivateEndpointConnections() .putWithResponseAsync(this.resourceGroupName(), this.name(), privateEndpointConnectionName, null, new PrivateLinkServiceConnectionState() .withStatus( PrivateEndpointServiceConnectionStatus.REJECTED)) .then(); } @Override public Mono<StorageAccount> refreshAsync() { return super .refreshAsync() .map( storageAccount -> { StorageAccountImpl impl = (StorageAccountImpl) storageAccount; impl.clearWrapperProperties(); return impl; }); } @Override protected Mono<StorageAccountInner> getInnerAsync() { return this.manager().serviceClient().getStorageAccounts().getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public StorageAccountImpl withSku(StorageAccountSkuType sku) { if (isInCreateMode()) { createParameters.withSku(new Sku().withName(sku.name())); } else { updateParameters.withSku(new Sku().withName(sku.name())); } return this; } @Override public StorageAccountImpl withBlobStorageAccountKind() { createParameters.withKind(Kind.BLOB_STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKind() { createParameters.withKind(Kind.STORAGE); return this; } @Override public StorageAccountImpl withGeneralPurposeAccountKindV2() { createParameters.withKind(Kind.STORAGE_V2); return this; } @Override public StorageAccountImpl withBlockBlobStorageAccountKind() { createParameters.withKind(Kind.BLOCK_BLOB_STORAGE); return this; } @Override public StorageAccountImpl withFileStorageAccountKind() { createParameters.withKind(Kind.FILE_STORAGE); return this; } @Override public StorageAccountImpl withBlobEncryption() { this.encryptionHelper.withBlobEncryption(); return this; } @Override public StorageAccountImpl withFileEncryption() { this.encryptionHelper.withFileEncryption(); return this; } @Override public StorageAccountImpl withEncryptionKeyFromKeyVault(String keyVaultUri, String keyName, String keyVersion) { this.encryptionHelper.withEncryptionKeyFromKeyVault(keyVaultUri, keyName, keyVersion); return this; } @Override public StorageAccountImpl withoutBlobEncryption() { this.encryptionHelper.withoutBlobEncryption(); return this; } @Override public StorageAccountImpl withoutFileEncryption() { this.encryptionHelper.withoutFileEncryption(); return this; } private void clearWrapperProperties() { accountStatuses = null; publicEndpoints = null; } @Override public StorageAccountImpl update() { createParameters = null; updateParameters = new StorageAccountUpdateParameters(); this.networkRulesHelper = new StorageNetworkRulesHelper(this.updateParameters, this.innerModel()); this.encryptionHelper = new StorageEncryptionHelper(this.updateParameters, this.innerModel()); return super.update(); } @Override public StorageAccountImpl withCustomDomain(CustomDomain customDomain) { if (isInCreateMode()) { createParameters.withCustomDomain(customDomain); } else { updateParameters.withCustomDomain(customDomain); } return this; } @Override public StorageAccountImpl withCustomDomain(String name) { return withCustomDomain(new CustomDomain().withName(name)); } @Override public StorageAccountImpl withCustomDomain(String name, boolean useSubDomain) { return withCustomDomain(new CustomDomain().withName(name).withUseSubDomainName(useSubDomain)); } @Override public StorageAccountImpl withAccessTier(AccessTier accessTier) { if (isInCreateMode()) { createParameters.withAccessTier(accessTier); } else { if (this.innerModel().kind() != Kind.BLOB_STORAGE) { throw logger.logExceptionAsError(new UnsupportedOperationException( "Access tier can not be changed for general purpose storage accounts.")); } updateParameters.withAccessTier(accessTier); } return this; } @Override public StorageAccountImpl withSystemAssignedManagedServiceIdentity() { if (this.innerModel().identity() == null) { if (isInCreateMode()) { createParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } else { updateParameters.withIdentity(new Identity().withType(IdentityType.SYSTEM_ASSIGNED)); } } return this; } @Override public StorageAccountImpl withOnlyHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(true); } else { updateParameters.withEnableHttpsTrafficOnly(true); } return this; } @Override public StorageAccountImpl withHttpAndHttpsTraffic() { if (isInCreateMode()) { createParameters.withEnableHttpsTrafficOnly(false); } else { updateParameters.withEnableHttpsTrafficOnly(false); } return this; } @Override public StorageAccountImpl withMinimumTlsVersion(MinimumTlsVersion minimumTlsVersion) { if (isInCreateMode()) { createParameters.withMinimumTlsVersion(minimumTlsVersion); } else { updateParameters.withMinimumTlsVersion(minimumTlsVersion); } return this; } @Override public StorageAccountImpl enableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(true); } else { updateParameters.withAllowBlobPublicAccess(true); } return this; } @Override public StorageAccountImpl disableBlobPublicAccess() { if (isInCreateMode()) { createParameters.withAllowBlobPublicAccess(false); } else { updateParameters.withAllowBlobPublicAccess(false); } return this; } @Override public StorageAccountImpl enableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(true); } else { updateParameters.withAllowSharedKeyAccess(true); } return this; } @Override public StorageAccountImpl disableSharedKeyAccess() { if (isInCreateMode()) { createParameters.withAllowSharedKeyAccess(false); } else { updateParameters.withAllowSharedKeyAccess(false); } return this; } @Override public StorageAccountImpl withAccessFromAllNetworks() { this.networkRulesHelper.withAccessFromAllNetworks(); return this; } @Override public StorageAccountImpl withAccessFromSelectedNetworks() { this.networkRulesHelper.withAccessFromSelectedNetworks(); return this; } @Override public StorageAccountImpl withAccessFromNetworkSubnet(String subnetId) { this.networkRulesHelper.withAccessFromNetworkSubnet(subnetId); return this; } @Override public StorageAccountImpl withAccessFromIpAddress(String ipAddress) { this.networkRulesHelper.withAccessFromIpAddress(ipAddress); return this; } @Override public StorageAccountImpl withAccessFromIpAddressRange(String ipAddressCidr) { this.networkRulesHelper.withAccessFromIpAddressRange(ipAddressCidr); return this; } @Override public StorageAccountImpl withReadAccessToLogEntriesFromAnyNetwork() { this.networkRulesHelper.withReadAccessToLoggingFromAnyNetwork(); return this; } @Override public StorageAccountImpl withReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withReadAccessToMetricsFromAnyNetwork(); return this; } @Override public StorageAccountImpl withAccessFromAzureServices() { this.networkRulesHelper.withAccessAllowedFromAzureServices(); return this; } @Override public StorageAccountImpl withoutNetworkSubnetAccess(String subnetId) { this.networkRulesHelper.withoutNetworkSubnetAccess(subnetId); return this; } @Override public StorageAccountImpl withoutIpAddressAccess(String ipAddress) { this.networkRulesHelper.withoutIpAddressAccess(ipAddress); return this; } @Override public StorageAccountImpl withoutIpAddressRangeAccess(String ipAddressCidr) { this.networkRulesHelper.withoutIpAddressRangeAccess(ipAddressCidr); return this; } @Override public Update withoutReadAccessToLoggingFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToLoggingFromAnyNetwork(); return this; } @Override public Update withoutReadAccessToMetricsFromAnyNetwork() { this.networkRulesHelper.withoutReadAccessToMetricsFromAnyNetwork(); return this; } @Override public Update withoutAccessFromAzureServices() { this.networkRulesHelper.withoutAccessFromAzureServices(); return this; } @Override public Update upgradeToGeneralPurposeAccountKindV2() { updateParameters.withKind(Kind.STORAGE_V2); return this; } @Override public Mono<StorageAccount> createResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); createParameters.withLocation(this.regionName()); createParameters.withTags(this.innerModel().tags()); final StorageAccountsClient client = this.manager().serviceClient().getStorageAccounts(); return this .manager() .serviceClient() .getStorageAccounts() .createAsync(this.resourceGroupName(), this.name(), createParameters) .flatMap( storageAccountInner -> client .getByResourceGroupAsync(resourceGroupName(), this.name()) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties())); } @Override public Mono<StorageAccount> updateResourceAsync() { this.networkRulesHelper.setDefaultActionIfRequired(); updateParameters.withTags(this.innerModel().tags()); return this .manager() .serviceClient() .getStorageAccounts() .updateAsync(resourceGroupName(), this.name(), updateParameters) .map(innerToFluentMap(this)) .doOnNext(storageAccount -> clearWrapperProperties()); } @Override public StorageAccountImpl withAzureFilesAadIntegrationEnabled(boolean enabled) { if (isInCreateMode()) { if (enabled) { this .createParameters .withAzureFilesIdentityBasedAuthentication( new AzureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS)); } } else { if (this.createParameters.azureFilesIdentityBasedAuthentication() == null) { this .createParameters .withAzureFilesIdentityBasedAuthentication(new AzureFilesIdentityBasedAuthentication()); } if (enabled) { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.AADDS); } else { this .updateParameters .azureFilesIdentityBasedAuthentication() .withDirectoryServiceOptions(DirectoryServiceOptions.NONE); } } return this; } @Override public StorageAccountImpl withLargeFileShares(boolean enabled) { if (isInCreateMode()) { if (enabled) { this.createParameters.withLargeFileSharesState(LargeFileSharesState.ENABLED); } else { this.createParameters.withLargeFileSharesState(LargeFileSharesState.DISABLED); } } return this; } @Override public StorageAccountImpl withHnsEnabled(boolean enabled) { this.createParameters.withIsHnsEnabled(enabled); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel; private PrivateLinkResourceImpl(com.azure.resourcemanager.storage.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.requiredZoneNames()); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
These validations were focusing on the input being non-null. Now the inputs have default values, so validation no longer needed.
public DeviceCodeCredential build() { String clientId = this.clientId != null ? this.clientId : IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID; return new DeviceCodeCredential(clientId, tenantId, challengeConsumer, automaticAuthentication, identityClientOptions); }
return new DeviceCodeCredential(clientId, tenantId, challengeConsumer, automaticAuthentication,
public DeviceCodeCredential build() { String clientId = this.clientId != null ? this.clientId : IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID; return new DeviceCodeCredential(clientId, tenantId, challengeConsumer, automaticAuthentication, identityClientOptions); }
class DeviceCodeCredentialBuilder extends AadCredentialBuilderBase<DeviceCodeCredentialBuilder> { private Consumer<DeviceCodeInfo> challengeConsumer = deviceCodeInfo -> System.out.println(deviceCodeInfo.getMessage()); private boolean automaticAuthentication = true; /** * Sets the consumer to meet the device code challenge. If not specified a default consumer is used which prints * the device code info message to stdout. * * @param challengeConsumer A method allowing the user to meet the device code challenge. * @return the InteractiveBrowserCredentialBuilder itself */ public DeviceCodeCredentialBuilder challengeConsumer( Consumer<DeviceCodeInfo> challengeConsumer) { this.challengeConsumer = challengeConsumer; return this; } /** * Configures the persistent shared token cache options and enables the persistent token cache which is disabled * by default. If configured, the credential will store tokens in a cache persisted to the machine, protected to * the current user, which can be shared by other credentials and processes. * * @param tokenCachePersistenceOptions the token cache configuration options * @return An updated instance of this builder with the token cache options configured. */ public DeviceCodeCredentialBuilder tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.identityClientOptions.setTokenCacheOptions(tokenCachePersistenceOptions); return this; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord the authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public DeviceCodeCredentialBuilder authenticationRecord(AuthenticationRecord authenticationRecord) { this.identityClientOptions.setAuthenticationRecord(authenticationRecord); return this; } /** * Disables the automatic authentication and prevents the {@link DeviceCodeCredential} from automatically * prompting the user. If automatic authentication is disabled a {@link AuthenticationRequiredException} * will be thrown from {@link DeviceCodeCredential * user interaction is necessary. The application is responsible for handling this exception, and * calling {@link DeviceCodeCredential * {@link DeviceCodeCredential * * @return An updated instance of this builder with automatic authentication disabled. */ public DeviceCodeCredentialBuilder disableAutomaticAuthentication() { this.automaticAuthentication = false; return this; } /** * Creates a new {@link DeviceCodeCredential} with the current configurations. * * @return a {@link DeviceCodeCredential} with the current configurations. */ }
class DeviceCodeCredentialBuilder extends AadCredentialBuilderBase<DeviceCodeCredentialBuilder> { private Consumer<DeviceCodeInfo> challengeConsumer = deviceCodeInfo -> System.out.println(deviceCodeInfo.getMessage()); private boolean automaticAuthentication = true; /** * Sets the consumer to meet the device code challenge. If not specified a default consumer is used which prints * the device code info message to stdout. * * @param challengeConsumer A method allowing the user to meet the device code challenge. * @return the InteractiveBrowserCredentialBuilder itself */ public DeviceCodeCredentialBuilder challengeConsumer( Consumer<DeviceCodeInfo> challengeConsumer) { this.challengeConsumer = challengeConsumer; return this; } /** * Configures the persistent shared token cache options and enables the persistent token cache which is disabled * by default. If configured, the credential will store tokens in a cache persisted to the machine, protected to * the current user, which can be shared by other credentials and processes. * * @param tokenCachePersistenceOptions the token cache configuration options * @return An updated instance of this builder with the token cache options configured. */ public DeviceCodeCredentialBuilder tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.identityClientOptions.setTokenCacheOptions(tokenCachePersistenceOptions); return this; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord the authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public DeviceCodeCredentialBuilder authenticationRecord(AuthenticationRecord authenticationRecord) { this.identityClientOptions.setAuthenticationRecord(authenticationRecord); return this; } /** * Disables the automatic authentication and prevents the {@link DeviceCodeCredential} from automatically * prompting the user. If automatic authentication is disabled a {@link AuthenticationRequiredException} * will be thrown from {@link DeviceCodeCredential * user interaction is necessary. The application is responsible for handling this exception, and * calling {@link DeviceCodeCredential * {@link DeviceCodeCredential * * @return An updated instance of this builder with automatic authentication disabled. */ public DeviceCodeCredentialBuilder disableAutomaticAuthentication() { this.automaticAuthentication = false; return this; } /** * Creates a new {@link DeviceCodeCredential} with the current configurations. * * @return a {@link DeviceCodeCredential} with the current configurations. */ }
Can a virtual directory have more than one item?
DirectoryStatus checkDirStatus() throws IOException { if (this.blobClient == null) { throw LoggingUtility.logError(logger, new IllegalArgumentException("The blob client was null.")); } BlobContainerClient containerClient = this.getContainerClient(); ListBlobsOptions listOptions = new ListBlobsOptions().setMaxResultsPerPage(2) .setPrefix(this.blobClient.getBlobName()) .setDetails(new BlobListDetails().setRetrieveMetadata(true)); /* Do a list on prefix. Zero elements means no virtual dir. Does not exist. One element that matches this dir means empty. One element that doesn't match this dir or more than one element. Not empty. One element that matches the name but does not have a directory marker means the resource is not a directory. Note that blob names that match the prefix exactly are returned in listing operations. */ try { Iterator<BlobItem> blobIterator = containerClient.listBlobsByHierarchy(AzureFileSystem.PATH_SEPARATOR, listOptions, null).iterator(); if (!blobIterator.hasNext()) { return DirectoryStatus.DOES_NOT_EXIST; } else { BlobItem item = blobIterator.next(); if (!item.getName().equals(this.blobClient.getBlobName())) { /* Names do not match. Must be a virtual dir with one item. e.g. blob with name "foo/bar" means dir "foo" exists. */ return DirectoryStatus.NOT_EMPTY; } if (item.getMetadata() != null && item.getMetadata().containsKey(DIR_METADATA_MARKER)) { if (blobIterator.hasNext()) { return DirectoryStatus.NOT_EMPTY; } else { return DirectoryStatus.EMPTY; } } return DirectoryStatus.NOT_A_DIRECTORY; } } catch (BlobStorageException e) { throw LoggingUtility.logError(logger, new IOException(e)); } }
Names do not match. Must be a virtual dir with one item. e.g. blob with name "foo/bar" means dir
DirectoryStatus checkDirStatus() throws IOException { if (this.blobClient == null) { throw LoggingUtility.logError(logger, new IllegalArgumentException("The blob client was null.")); } BlobContainerClient containerClient = this.getContainerClient(); ListBlobsOptions listOptions = new ListBlobsOptions().setMaxResultsPerPage(2) .setPrefix(this.blobClient.getBlobName()) .setDetails(new BlobListDetails().setRetrieveMetadata(true)); /* Do a list on prefix. Zero elements means no virtual dir. Does not exist. One element that matches this dir means empty. One element that doesn't match this dir or more than one element. Not empty. One element that matches the name but does not have a directory marker means the resource is not a directory. Note that blob names that match the prefix exactly are returned in listing operations. */ try { Iterator<BlobItem> blobIterator = containerClient.listBlobsByHierarchy(AzureFileSystem.PATH_SEPARATOR, listOptions, null).iterator(); if (!blobIterator.hasNext()) { return DirectoryStatus.DOES_NOT_EXIST; } else { BlobItem item = blobIterator.next(); if (!item.getName().equals(this.blobClient.getBlobName())) { /* Names do not match. Must be a virtual dir with one item. e.g. blob with name "foo/bar" means dir "foo" exists. */ return DirectoryStatus.NOT_EMPTY; } if (item.getMetadata() != null && item.getMetadata().containsKey(DIR_METADATA_MARKER)) { if (blobIterator.hasNext()) { return DirectoryStatus.NOT_EMPTY; } else { return DirectoryStatus.EMPTY; } } return DirectoryStatus.NOT_A_DIRECTORY; } } catch (BlobStorageException e) { throw LoggingUtility.logError(logger, new IOException(e)); } }
class AzureResource { private final ClientLogger logger = new ClientLogger(AzureResource.class); static final String DIR_METADATA_MARKER = Constants.HeaderConstants.DIRECTORY_METADATA_KEY; private final AzurePath path; private final BlobClient blobClient; private BlobHttpHeaders blobHeaders; private Map<String, String> blobMetadata; AzureResource(Path path) throws IOException { Objects.requireNonNull(path, "path"); this.path = validatePathInstanceType(path); this.validateNotRoot(); this.blobClient = this.path.toBlobClient(); } /** * Checks for the existence of the parent of the given path. We do not check for the actual marker blob as parents * need only weakly exist. * * If the parent is a root (container), it will be assumed to exist, so it must be validated elsewhere that the * container is a legitimate root within this file system. */ boolean checkParentDirectoryExists() throws IOException { /* If the parent is just the root (or null, which means the parent is implicitly the default directory which is a root), that means we are checking a container, which is always considered to exist. Otherwise, perform normal existence check. */ Path parent = this.path.getParent(); return (parent == null || parent.equals(path.getRoot())) || new AzureResource(this.path.getParent()).checkDirectoryExists(); } /** * Checks whether a directory exists by either being empty or having children. */ boolean checkDirectoryExists() throws IOException { DirectoryStatus dirStatus = this.checkDirStatus(); return dirStatus.equals(DirectoryStatus.EMPTY) || dirStatus.equals(DirectoryStatus.NOT_EMPTY); } /** * This method will check if a directory is extant and/or empty and accommodates virtual directories. This method * will not check the status of root directories. */ /** * Creates the actual directory marker. This method should only be used when any necessary checks for proper * conditions of directory creation (e.g. parent existence) have already been performed. Otherwise, * {@link AzureFileSystemProvider * * @param requestConditions Any necessary request conditions to pass when creating the directory blob. */ void putDirectoryBlob(BlobRequestConditions requestConditions) { this.blobClient.getBlockBlobClient().commitBlockListWithResponse(Collections.emptyList(), this.blobHeaders, this.prepareMetadataForDirectory(), null, requestConditions, null, null); } /* Note that this will remove the properties from the list of attributes as it finds them. */ private void extractHttpHeaders(List<FileAttribute<?>> fileAttributes) { BlobHttpHeaders headers = new BlobHttpHeaders(); for (Iterator<FileAttribute<?>> it = fileAttributes.iterator(); it.hasNext();) { FileAttribute<?> attr = it.next(); boolean propertyFound = true; switch (attr.name()) { case AzureFileSystemProvider.CONTENT_TYPE: headers.setContentType(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_LANGUAGE: headers.setContentLanguage(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_DISPOSITION: headers.setContentDisposition(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_ENCODING: headers.setContentEncoding(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_MD5: if ((attr.value() instanceof byte[])) { headers.setContentMd5((byte[]) attr.value()); } else { throw LoggingUtility.logError(logger, new UnsupportedOperationException("Content-MD5 attribute must be a byte[]")); } break; case AzureFileSystemProvider.CACHE_CONTROL: headers.setCacheControl(attr.value().toString()); break; default: propertyFound = false; break; } if (propertyFound) { it.remove(); } } this.blobHeaders = headers; } /** * Note this should only be used after the headers have been extracted. * * @param fileAttributes The attributes to convert to metadata. */ private void convertAttributesToMetadata(List<FileAttribute<?>> fileAttributes) { Map<String, String> metadata = new HashMap<>(); for (FileAttribute<?> attr : fileAttributes) { metadata.put(attr.name(), attr.value().toString()); } this.blobMetadata = metadata.isEmpty() ? null : metadata; } private void validateNotRoot() { if (this.path.isRoot()) { throw LoggingUtility.logError(logger, new IllegalArgumentException( "Root directory not supported. Path: " + this.path.toString())); } } private AzurePath validatePathInstanceType(Path path) { if (!(path instanceof AzurePath)) { throw LoggingUtility.logError(logger, new IllegalArgumentException("This provider cannot operate on " + "subtypes of Path other than AzurePath")); } return (AzurePath) path; } BlobContainerClient getContainerClient() { return new BlobContainerClientBuilder().endpoint(this.blobClient.getBlobUrl()) .pipeline(this.blobClient.getHttpPipeline()) .buildClient(); } AzureResource setFileAttributes(List<FileAttribute<?>> attributes) { attributes = new ArrayList<>(attributes); extractHttpHeaders(attributes); convertAttributesToMetadata(attributes); return this; } AzurePath getPath() { return this.path; } BlobClient getBlobClient() { return this.blobClient; } BlobOutputStream getBlobOutputStream(ParallelTransferOptions pto, BlobRequestConditions rq) { BlockBlobOutputStreamOptions options = new BlockBlobOutputStreamOptions() .setHeaders(this.blobHeaders) .setMetadata(this.blobMetadata) .setParallelTransferOptions(pto) .setRequestConditions(rq); return this.blobClient.getBlockBlobClient().getBlobOutputStream(options); } private Map<String, String> prepareMetadataForDirectory() { if (this.blobMetadata == null) { this.blobMetadata = new HashMap<>(); } this.blobMetadata.put(DIR_METADATA_MARKER, "true"); return this.blobMetadata; } }
class AzureResource { private final ClientLogger logger = new ClientLogger(AzureResource.class); static final String DIR_METADATA_MARKER = Constants.HeaderConstants.DIRECTORY_METADATA_KEY; private final AzurePath path; private final BlobClient blobClient; private BlobHttpHeaders blobHeaders; private Map<String, String> blobMetadata; AzureResource(Path path) throws IOException { Objects.requireNonNull(path, "path"); this.path = validatePathInstanceType(path); this.validateNotRoot(); this.blobClient = this.path.toBlobClient(); } /** * Checks for the existence of the parent of the given path. We do not check for the actual marker blob as parents * need only weakly exist. * * If the parent is a root (container), it will be assumed to exist, so it must be validated elsewhere that the * container is a legitimate root within this file system. */ boolean checkParentDirectoryExists() throws IOException { /* If the parent is just the root (or null, which means the parent is implicitly the default directory which is a root), that means we are checking a container, which is always considered to exist. Otherwise, perform normal existence check. */ Path parent = this.path.getParent(); return (parent == null || parent.equals(path.getRoot())) || new AzureResource(this.path.getParent()).checkDirectoryExists(); } /** * Checks whether a directory exists by either being empty or having children. */ boolean checkDirectoryExists() throws IOException { DirectoryStatus dirStatus = this.checkDirStatus(); return dirStatus.equals(DirectoryStatus.EMPTY) || dirStatus.equals(DirectoryStatus.NOT_EMPTY); } /** * This method will check if a directory is extant and/or empty and accommodates virtual directories. This method * will not check the status of root directories. */ /** * Creates the actual directory marker. This method should only be used when any necessary checks for proper * conditions of directory creation (e.g. parent existence) have already been performed. Otherwise, * {@link AzureFileSystemProvider * * @param requestConditions Any necessary request conditions to pass when creating the directory blob. */ void putDirectoryBlob(BlobRequestConditions requestConditions) { this.blobClient.getBlockBlobClient().commitBlockListWithResponse(Collections.emptyList(), this.blobHeaders, this.prepareMetadataForDirectory(), null, requestConditions, null, null); } /* Note that this will remove the properties from the list of attributes as it finds them. */ private void extractHttpHeaders(List<FileAttribute<?>> fileAttributes) { BlobHttpHeaders headers = new BlobHttpHeaders(); for (Iterator<FileAttribute<?>> it = fileAttributes.iterator(); it.hasNext();) { FileAttribute<?> attr = it.next(); boolean propertyFound = true; switch (attr.name()) { case AzureFileSystemProvider.CONTENT_TYPE: headers.setContentType(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_LANGUAGE: headers.setContentLanguage(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_DISPOSITION: headers.setContentDisposition(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_ENCODING: headers.setContentEncoding(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_MD5: if ((attr.value() instanceof byte[])) { headers.setContentMd5((byte[]) attr.value()); } else { throw LoggingUtility.logError(logger, new UnsupportedOperationException("Content-MD5 attribute must be a byte[]")); } break; case AzureFileSystemProvider.CACHE_CONTROL: headers.setCacheControl(attr.value().toString()); break; default: propertyFound = false; break; } if (propertyFound) { it.remove(); } } this.blobHeaders = headers; } /** * Note this should only be used after the headers have been extracted. * * @param fileAttributes The attributes to convert to metadata. */ private void convertAttributesToMetadata(List<FileAttribute<?>> fileAttributes) { Map<String, String> metadata = new HashMap<>(); for (FileAttribute<?> attr : fileAttributes) { metadata.put(attr.name(), attr.value().toString()); } this.blobMetadata = metadata.isEmpty() ? null : metadata; } private void validateNotRoot() { if (this.path.isRoot()) { throw LoggingUtility.logError(logger, new IllegalArgumentException( "Root directory not supported. Path: " + this.path.toString())); } } private AzurePath validatePathInstanceType(Path path) { if (!(path instanceof AzurePath)) { throw LoggingUtility.logError(logger, new IllegalArgumentException("This provider cannot operate on " + "subtypes of Path other than AzurePath")); } return (AzurePath) path; } BlobContainerClient getContainerClient() { return new BlobContainerClientBuilder().endpoint(this.blobClient.getBlobUrl()) .pipeline(this.blobClient.getHttpPipeline()) .buildClient(); } AzureResource setFileAttributes(List<FileAttribute<?>> attributes) { attributes = new ArrayList<>(attributes); extractHttpHeaders(attributes); convertAttributesToMetadata(attributes); return this; } AzurePath getPath() { return this.path; } BlobClient getBlobClient() { return this.blobClient; } BlobOutputStream getBlobOutputStream(ParallelTransferOptions pto, BlobRequestConditions rq) { BlockBlobOutputStreamOptions options = new BlockBlobOutputStreamOptions() .setHeaders(this.blobHeaders) .setMetadata(this.blobMetadata) .setParallelTransferOptions(pto) .setRequestConditions(rq); return this.blobClient.getBlockBlobClient().getBlobOutputStream(options); } private Map<String, String> prepareMetadataForDirectory() { if (this.blobMetadata == null) { this.blobMetadata = new HashMap<>(); } this.blobMetadata.put(DIR_METADATA_MARKER, "true"); return this.blobMetadata; } }
The generated method reference apparently causes a compilation failure with Java 8 as `Mono` has a public method `empty()` and an internal method `empty(Publisher<T>)` which leads to an ambiguous call. https://github.com/reactor/reactor-core/blame/master/reactor-core/src/main/java/reactor/core/publisher/Mono.java#L4905 cc: @srnagar @weidongxu-microsoft
private PagedIterableImpl(PagedIterable<T> pageIterable, Function<T, S> mapper) { super(new PagedFlux<S>(() -> Mono.empty())); this.pageIterable = pageIterable; this.mapper = mapper; this.pageMapper = page -> new PagedResponseBase<Void, S>( page.getRequest(), page.getStatusCode(), page.getHeaders(), page.getElements().stream().map(mapper).collect(Collectors.toList()), page.getContinuationToken(), null); }
super(new PagedFlux<S>(() -> Mono.empty()));
private PagedIterableImpl(PagedIterable<T> pageIterable, Function<T, S> mapper) { super(new PagedFlux<S>(() -> Mono.empty())); this.pageIterable = pageIterable; this.mapper = mapper; this.pageMapper = page -> new PagedResponseBase<Void, S>( page.getRequest(), page.getStatusCode(), page.getHeaders(), page.getElements().stream().map(mapper).collect(Collectors.toList()), page.getContinuationToken(), null); }
class PagedIterableImpl<T, S> extends PagedIterable<S> { private final PagedIterable<T> pageIterable; private final Function<T, S> mapper; private final Function<PagedResponse<T>, PagedResponse<S>> pageMapper; @Override public Stream<S> stream() { return pageIterable.stream().map(mapper); } @Override public Stream<PagedResponse<S>> streamByPage() { return pageIterable.streamByPage().map(pageMapper); } @Override public Stream<PagedResponse<S>> streamByPage(String continuationToken) { return pageIterable.streamByPage(continuationToken).map(pageMapper); } @Override public Stream<PagedResponse<S>> streamByPage(int preferredPageSize) { return pageIterable.streamByPage(preferredPageSize).map(pageMapper); } @Override public Stream<PagedResponse<S>> streamByPage(String continuationToken, int preferredPageSize) { return pageIterable.streamByPage(continuationToken, preferredPageSize).map(pageMapper); } @Override public Iterator<S> iterator() { return new IteratorImpl<T, S>(pageIterable.iterator(), mapper); } @Override public Iterable<PagedResponse<S>> iterableByPage() { return new IterableImpl<PagedResponse<T>, PagedResponse<S>>(pageIterable.iterableByPage(), pageMapper); } @Override public Iterable<PagedResponse<S>> iterableByPage(String continuationToken) { return new IterableImpl<PagedResponse<T>, PagedResponse<S>>( pageIterable.iterableByPage(continuationToken), pageMapper); } @Override public Iterable<PagedResponse<S>> iterableByPage(int preferredPageSize) { return new IterableImpl<PagedResponse<T>, PagedResponse<S>>( pageIterable.iterableByPage(preferredPageSize), pageMapper); } @Override public Iterable<PagedResponse<S>> iterableByPage(String continuationToken, int preferredPageSize) { return new IterableImpl<PagedResponse<T>, PagedResponse<S>>( pageIterable.iterableByPage(continuationToken, preferredPageSize), pageMapper); } }
class PagedIterableImpl<T, S> extends PagedIterable<S> { private final PagedIterable<T> pageIterable; private final Function<T, S> mapper; private final Function<PagedResponse<T>, PagedResponse<S>> pageMapper; @Override public Stream<S> stream() { return pageIterable.stream().map(mapper); } @Override public Stream<PagedResponse<S>> streamByPage() { return pageIterable.streamByPage().map(pageMapper); } @Override public Stream<PagedResponse<S>> streamByPage(String continuationToken) { return pageIterable.streamByPage(continuationToken).map(pageMapper); } @Override public Stream<PagedResponse<S>> streamByPage(int preferredPageSize) { return pageIterable.streamByPage(preferredPageSize).map(pageMapper); } @Override public Stream<PagedResponse<S>> streamByPage(String continuationToken, int preferredPageSize) { return pageIterable.streamByPage(continuationToken, preferredPageSize).map(pageMapper); } @Override public Iterator<S> iterator() { return new IteratorImpl<T, S>(pageIterable.iterator(), mapper); } @Override public Iterable<PagedResponse<S>> iterableByPage() { return new IterableImpl<PagedResponse<T>, PagedResponse<S>>(pageIterable.iterableByPage(), pageMapper); } @Override public Iterable<PagedResponse<S>> iterableByPage(String continuationToken) { return new IterableImpl<PagedResponse<T>, PagedResponse<S>>( pageIterable.iterableByPage(continuationToken), pageMapper); } @Override public Iterable<PagedResponse<S>> iterableByPage(int preferredPageSize) { return new IterableImpl<PagedResponse<T>, PagedResponse<S>>( pageIterable.iterableByPage(preferredPageSize), pageMapper); } @Override public Iterable<PagedResponse<S>> iterableByPage(String continuationToken, int preferredPageSize) { return new IterableImpl<PagedResponse<T>, PagedResponse<S>>( pageIterable.iterableByPage(continuationToken, preferredPageSize), pageMapper); } }
```suggestion Objects.requireNonNull(encryptParameters, "'encryptParameters' cannot be null"); ```
public Mono<EncryptResult> encrypt(EncryptParameters encryptParameters) { Objects.requireNonNull(encryptParameters, "'encryptOptions' cannot be null"); try { return withContext(context -> encrypt(encryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Objects.requireNonNull(encryptParameters, "'encryptOptions' cannot be null");
public Mono<EncryptResult> encrypt(EncryptParameters encryptParameters) { Objects.requireNonNull(encryptParameters, "'encryptParameters' cannot be null"); try { return withContext(context -> encrypt(encryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private String keyCollection; private final String keyId; /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param jsonWebKey the json web key to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(JsonWebKey jsonWebKey, HttpPipeline pipeline, CryptographyServiceVersion version) { Objects.requireNonNull(jsonWebKey, "The Json web key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = jsonWebKey; this.keyId = key.getId(); service = pipeline != null ? RestProxy.create(CryptographyService.class, pipeline) : null; if (!Strings.isNullOrEmpty(key.getId()) && version != null && service != null) { unpackAndValidateId(key.getId()); cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service, version); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param keyId THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The Json Web Key Type: %s is not supported.", key.getKeyType().toString()))); } } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(context -> getKeyWithResponse(context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plainText The content to be encrypted. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plainText) { return encrypt(new EncryptParameters(algorithm, plainText, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptParameters The parameters to use in the encryption operation. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code encryptParameters} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<EncryptResult> encrypt(EncryptParameters encryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt Operation is missing permission/not supported for key with id %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptParameters, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(new DecryptParameters(algorithm, cipherText, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptParameters The parameters to use in the decryption operation. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code decryptParameters} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptParameters decryptParameters) { Objects.requireNonNull(decryptParameters, "'decryptOptions' cannot be null"); try { return withContext(context -> decrypt(decryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptParameters decryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt Operation is not allowed for key with id %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptParameters, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation * requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for " + "key with id %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is * the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @return A {@link Mono} containing a the unwrapped key content. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm} or {@code data} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires * the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @return The {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e)); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private String keyCollection; private final String keyId; private final HttpPipeline pipeline; /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param jsonWebKey the json web key to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(JsonWebKey jsonWebKey, HttpPipeline pipeline, CryptographyServiceVersion version) { Objects.requireNonNull(jsonWebKey, "The Json web key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = jsonWebKey; this.keyId = key.getId(); this.pipeline = pipeline; service = pipeline != null ? RestProxy.create(CryptographyService.class, pipeline) : null; if (!Strings.isNullOrEmpty(key.getId()) && version != null && service != null) { unpackAndValidateId(key.getId()); cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service, version); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param keyId THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.pipeline = pipeline; service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The Json Web Key Type: %s is not supported.", key.getKeyType().toString()))); } } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(context -> getKeyWithResponse(context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(new EncryptParameters(algorithm, plaintext, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptParameters The parameters to use in the encryption operation. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code encryptParameters} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<EncryptResult> encrypt(EncryptParameters encryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt Operation is missing permission/not supported for key with id %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptParameters, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { return decrypt(new DecryptParameters(algorithm, ciphertext, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptParameters The parameters to use in the decryption operation. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code decryptParameters} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptParameters decryptParameters) { Objects.requireNonNull(decryptParameters, "'decryptParameters' cannot be null"); try { return withContext(context -> decrypt(decryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptParameters decryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt Operation is not allowed for key with id %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptParameters, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation * requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for " + "key with id %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is * the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @return A {@link Mono} containing a the unwrapped key content. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm} or {@code data} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires * the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @return The {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e)); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
```suggestion Objects.requireNonNull(decryptParameters, "'decryptParameters' cannot be null"); ```
public Mono<DecryptResult> decrypt(DecryptParameters decryptParameters) { Objects.requireNonNull(decryptParameters, "'decryptOptions' cannot be null"); try { return withContext(context -> decrypt(decryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Objects.requireNonNull(decryptParameters, "'decryptOptions' cannot be null");
public Mono<DecryptResult> decrypt(DecryptParameters decryptParameters) { Objects.requireNonNull(decryptParameters, "'decryptParameters' cannot be null"); try { return withContext(context -> decrypt(decryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private String keyCollection; private final String keyId; /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param jsonWebKey the json web key to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(JsonWebKey jsonWebKey, HttpPipeline pipeline, CryptographyServiceVersion version) { Objects.requireNonNull(jsonWebKey, "The Json web key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = jsonWebKey; this.keyId = key.getId(); service = pipeline != null ? RestProxy.create(CryptographyService.class, pipeline) : null; if (!Strings.isNullOrEmpty(key.getId()) && version != null && service != null) { unpackAndValidateId(key.getId()); cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service, version); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param keyId THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The Json Web Key Type: %s is not supported.", key.getKeyType().toString()))); } } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(context -> getKeyWithResponse(context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plainText The content to be encrypted. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plainText) { return encrypt(new EncryptParameters(algorithm, plainText, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptParameters The parameters to use in the encryption operation. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code encryptParameters} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptParameters encryptParameters) { Objects.requireNonNull(encryptParameters, "'encryptOptions' cannot be null"); try { return withContext(context -> encrypt(encryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptParameters encryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt Operation is missing permission/not supported for key with id %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptParameters, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(new DecryptParameters(algorithm, cipherText, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptParameters The parameters to use in the decryption operation. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code decryptParameters} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<DecryptResult> decrypt(DecryptParameters decryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt Operation is not allowed for key with id %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptParameters, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation * requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for " + "key with id %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is * the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @return A {@link Mono} containing a the unwrapped key content. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm} or {@code data} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires * the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @return The {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e)); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private String keyCollection; private final String keyId; private final HttpPipeline pipeline; /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param jsonWebKey the json web key to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(JsonWebKey jsonWebKey, HttpPipeline pipeline, CryptographyServiceVersion version) { Objects.requireNonNull(jsonWebKey, "The Json web key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = jsonWebKey; this.keyId = key.getId(); this.pipeline = pipeline; service = pipeline != null ? RestProxy.create(CryptographyService.class, pipeline) : null; if (!Strings.isNullOrEmpty(key.getId()) && version != null && service != null) { unpackAndValidateId(key.getId()); cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service, version); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param keyId THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.pipeline = pipeline; service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The Json Web Key Type: %s is not supported.", key.getKeyType().toString()))); } } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(context -> getKeyWithResponse(context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(new EncryptParameters(algorithm, plaintext, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptParameters The parameters to use in the encryption operation. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code encryptParameters} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptParameters encryptParameters) { Objects.requireNonNull(encryptParameters, "'encryptParameters' cannot be null"); try { return withContext(context -> encrypt(encryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptParameters encryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt Operation is missing permission/not supported for key with id %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptParameters, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { return decrypt(new DecryptParameters(algorithm, ciphertext, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptParameters The parameters to use in the decryption operation. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. * @throws NullPointerException If {@code decryptParameters} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<DecryptResult> decrypt(DecryptParameters decryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt Operation is not allowed for key with id %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptParameters, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation * requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for " + "key with id %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is * the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @return A {@link Mono} containing a the unwrapped key content. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm} or {@code data} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires * the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * ES512}, {@link SignatureAlgorithm * SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @return The {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify Operation is not allowed for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e)); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
This logic differs from other clients where `HttpClient`, and same below with `HttpPipeline`, are allowed to be null given that default values will be used if they aren't configured. https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java#L340
public KeyVaultAccessControlClientBuilder httpClient(HttpClient client) { if (client == null) { throw logger.logExceptionAsError(new NullPointerException("'client' cannot be null.")); } this.httpClient = client; return this; }
throw logger.logExceptionAsError(new NullPointerException("'client' cannot be null."));
public KeyVaultAccessControlClientBuilder httpClient(HttpClient client) { this.httpClient = client; return this; }
class KeyVaultAccessControlClientBuilder { private static final String AZURE_KEY_VAULT_RBAC = "azure-key-vault-administration.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final ClientLogger logger = new ClientLogger(KeyVaultAccessControlClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies; private final List<HttpPipelinePolicy> perRetryPolicies; private final Map<String, String> properties; private TokenCredential credential; private HttpPipeline pipeline; private URL vaultUrl; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private KeyVaultAdministrationServiceVersion serviceVersion; /** * Creates a {@link KeyVaultAccessControlClientBuilder} instance that is able to configure and construct * instances of {@link KeyVaultAccessControlClient} and {@link KeyVaultAccessControlAsyncClient}. */ public KeyVaultAccessControlClientBuilder() { retryPolicy = new RetryPolicy(); httpLogOptions = new HttpLogOptions(); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); properties = CoreUtils.getProperties(AZURE_KEY_VAULT_RBAC); } /** * Creates an {@link KeyVaultAccessControlClient} based on options set in the Builder. Every time {@code * buildClient()} is called a new instance of {@link KeyVaultAccessControlClient} is created. * <p> * If {@link * {@link * builder settings are ignored. * * @return An {@link KeyVaultAccessControlClient} with the options set from the builder. * * @throws NullPointerException If {@code vaultUrl} is {@code null}. */ public KeyVaultAccessControlClient buildClient() { return new KeyVaultAccessControlClient(buildAsyncClient()); } /** * Creates a {@link KeyVaultAccessControlAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link KeyVaultAccessControlAsyncClient} is created. * <p> * If {@link * {@link * other builder settings are ignored. * * @return An {@link KeyVaultAccessControlAsyncClient} with the options set from the builder. * * @throws NullPointerException If {@code vaultUrl} is {@code null}. */ public KeyVaultAccessControlAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; URL buildEndpoint = getBuildEndpoint(buildConfiguration); if (buildEndpoint == null) { throw logger.logExceptionAsError( new IllegalStateException( KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED))); } serviceVersion = serviceVersion != null ? serviceVersion : KeyVaultAdministrationServiceVersion.getLatest(); if (pipeline != null) { return new KeyVaultAccessControlAsyncClient(vaultUrl, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration)); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new KeyVaultAccessControlAsyncClient(vaultUrl, buildPipeline, serviceVersion); } /** * Sets the URL to the Key Vault on which the client operates. Appears as "DNS Name" in the Azure portal. * * @param vaultUrl The vault URL is used as destination on Azure to send requests to. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. * * @throws IllegalArgumentException If {@code vaultUrl} cannot be parsed into a valid URL. * @throws NullPointerException If {@code credential} is {@code null}. */ public KeyVaultAccessControlClientBuilder vaultUrl(String vaultUrl) { if (vaultUrl == null) { throw logger.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); } try { this.vaultUrl = new URL(vaultUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsError( new IllegalArgumentException("The Azure Key Vault URL is malformed.", e)); } return this; } /** * Sets the credential to use when authenticating HTTP requests. * * @param credential The credential to use for authenticating HTTP requests. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. * * @throws NullPointerException If {@code credential} is {@code null}. */ public KeyVaultAccessControlClientBuilder credential(TokenCredential credential) { if (credential == null) { throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); } this.credential = credential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after and {@link KeyVaultAccessControlClient} * {@link KeyVaultAccessControlAsyncClient} required policies. * * @param policy The {@link HttpPipelinePolicy policy} to be added. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. * * @throws NullPointerException If {@code policy} is {@code null}. */ public KeyVaultAccessControlClientBuilder addPolicy(HttpPipelinePolicy policy) { if (policy == null) { throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. * * @throws NullPointerException If {@code client} is {@code null}. */ /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link KeyVaultAccessControlClientBuilder * or {@link KeyVaultAccessControlAsyncClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. * * @throws NullPointerException If {@code pipeline} is {@code null}. */ public KeyVaultAccessControlClientBuilder pipeline(HttpPipeline pipeline) { if (pipeline == null) { throw logger.logExceptionAsError(new NullPointerException("'pipeline' cannot be null.")); } this.pipeline = pipeline; 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 get configuration details. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder 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 in the pipeline, if not provided. * * @param retryPolicy User's retry policy applied to each request. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. * * @throws NullPointerException If the specified {@code retryPolicy} is null. */ public KeyVaultAccessControlClientBuilder retryPolicy(RetryPolicy retryPolicy) { if (retryPolicy == null) { throw logger.logExceptionAsError(new NullPointerException("'retryPolicy' cannot be null.")); } this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * Telemetry policy</a> * * @param clientOptions the {@link ClientOptions} to be set on the client. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the {@link KeyVaultAdministrationServiceVersion} that is used when making API requests. * * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param serviceVersion {@link KeyVaultAdministrationServiceVersion} of the service API used when making requests. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder serviceVersion(KeyVaultAdministrationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } private URL getBuildEndpoint(Configuration configuration) { if (vaultUrl != null) { return vaultUrl; } String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); if (CoreUtils.isNullOrEmpty(configEndpoint)) { return null; } try { return new URL(configEndpoint); } catch (MalformedURLException ex) { return null; } } }
class KeyVaultAccessControlClientBuilder { private static final String AZURE_KEY_VAULT_RBAC = "azure-key-vault-administration.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final ClientLogger logger = new ClientLogger(KeyVaultAccessControlClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies; private final List<HttpPipelinePolicy> perRetryPolicies; private final Map<String, String> properties; private TokenCredential credential; private HttpPipeline pipeline; private URL vaultUrl; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private KeyVaultAdministrationServiceVersion serviceVersion; /** * Creates a {@link KeyVaultAccessControlClientBuilder} instance that is able to configure and construct * instances of {@link KeyVaultAccessControlClient} and {@link KeyVaultAccessControlAsyncClient}. */ public KeyVaultAccessControlClientBuilder() { retryPolicy = new RetryPolicy(); httpLogOptions = new HttpLogOptions(); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); properties = CoreUtils.getProperties(AZURE_KEY_VAULT_RBAC); } /** * Creates an {@link KeyVaultAccessControlClient} based on options set in the Builder. Every time {@code * buildClient()} is called a new instance of {@link KeyVaultAccessControlClient} is created. * <p> * If {@link * {@link * builder settings are ignored. * * @return An {@link KeyVaultAccessControlClient} with the options set from the builder. * * @throws NullPointerException If {@code vaultUrl} is {@code null}. */ public KeyVaultAccessControlClient buildClient() { return new KeyVaultAccessControlClient(buildAsyncClient()); } /** * Creates a {@link KeyVaultAccessControlAsyncClient} based on options set in the Builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link KeyVaultAccessControlAsyncClient} is created. * <p> * If {@link * {@link * other builder settings are ignored. * * @return An {@link KeyVaultAccessControlAsyncClient} with the options set from the builder. * * @throws NullPointerException If {@code vaultUrl} is {@code null}. */ public KeyVaultAccessControlAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; URL buildEndpoint = getBuildEndpoint(buildConfiguration); if (buildEndpoint == null) { throw logger.logExceptionAsError( new IllegalStateException( KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED))); } serviceVersion = serviceVersion != null ? serviceVersion : KeyVaultAdministrationServiceVersion.getLatest(); if (pipeline != null) { return new KeyVaultAccessControlAsyncClient(vaultUrl, pipeline, serviceVersion); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration)); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new KeyVaultAccessControlAsyncClient(vaultUrl, buildPipeline, serviceVersion); } /** * Sets the URL to the Key Vault on which the client operates. Appears as "DNS Name" in the Azure portal. * * @param vaultUrl The vault URL is used as destination on Azure to send requests to. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. * * @throws IllegalArgumentException If {@code vaultUrl} cannot be parsed into a valid URL. * @throws NullPointerException If {@code credential} is {@code null}. */ public KeyVaultAccessControlClientBuilder vaultUrl(String vaultUrl) { if (vaultUrl == null) { throw logger.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); } try { this.vaultUrl = new URL(vaultUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsError( new IllegalArgumentException("The Azure Key Vault URL is malformed.", e)); } return this; } /** * Sets the credential to use when authenticating HTTP requests. * * @param credential The credential to use for authenticating HTTP requests. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. * * @throws NullPointerException If {@code credential} is {@code null}. */ public KeyVaultAccessControlClientBuilder credential(TokenCredential credential) { if (credential == null) { throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); } this.credential = credential; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after and {@link KeyVaultAccessControlClient} * {@link KeyVaultAccessControlAsyncClient} required policies. * * @param policy The {@link HttpPipelinePolicy policy} to be added. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. * * @throws NullPointerException If {@code policy} is {@code null}. */ public KeyVaultAccessControlClientBuilder addPolicy(HttpPipelinePolicy policy) { if (policy == null) { throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link KeyVaultAccessControlClientBuilder * or {@link KeyVaultAccessControlAsyncClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; 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 get configuration details. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder 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 in the pipeline, if not provided. * * @param retryPolicy User's retry policy applied to each request. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * the {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * Telemetry policy</a> * * @param clientOptions the {@link ClientOptions} to be set on the client. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the {@link KeyVaultAdministrationServiceVersion} that is used when making API requests. * * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param serviceVersion {@link KeyVaultAdministrationServiceVersion} of the service API used when making requests. * * @return The updated {@link KeyVaultAccessControlClientBuilder} object. */ public KeyVaultAccessControlClientBuilder serviceVersion(KeyVaultAdministrationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } private URL getBuildEndpoint(Configuration configuration) { if (vaultUrl != null) { return vaultUrl; } String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); if (CoreUtils.isNullOrEmpty(configEndpoint)) { return null; } try { return new URL(configEndpoint); } catch (MalformedURLException ex) { return null; } } }
Is the registry actually the same as the endpoint? #Resolved
public String getRegistry() { return this.endpoint; }
return this.endpoint;
public String getRegistry() { return this.endpoint; }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializerAdapter) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } /** * Delete repository. * * @param context Context associated with the operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().map(Response::getValue); } /** * Delete registry artifact. * * @param digest Digest name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Delete tag. * * @param tag tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().map(Response::getValue); } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<String> getTagMono = Mono.defer( () -> tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest())); return getTagMono .flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).map(Response::getValue); } /** * List registry artifacts based of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List manifests of a repository. * * @param options the options associated with the list registy operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).map(Response::getValue); } /** * List tags of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value) .flatMap((Response<Void> res) -> Mono.empty()); } }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().flatMap(FluxUtil::toMono); } /** * Delete registry artifact. * * @param digest the digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest).flatMap(FluxUtil::toMono); } /** * Delete tag. * * @param tag tag to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag tag to delete * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag).flatMap(FluxUtil::toMono); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given repository was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { Mono<String> getTagMono = tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest()); return getTagMono .flatMap(digest -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, digest)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).flatMap(FluxUtil::toMono); } /** * List registry artifacts of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List registry artifacts of a repository. * * @param options the options associated with the list registry operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).flatMap(FluxUtil::toMono); } /** * List tags of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value).flatMap(FluxUtil::toMono); } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value).flatMap(FluxUtil::toMono); } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value).flatMap(FluxUtil::toMono); } }
Whether this should be calling into the parent or not, I don't see getters for other properties. Shouldn't there be? In .NET, we almost never have write-only properties: just read-only or read-write.
public Integer getKeySize() { return this.keySize; }
return this.keySize;
public Integer getKeySize() { return this.keySize; }
class CreateOctKeyOptions extends CreateKeyOptions { /** * The AES key size. */ private Integer keySize; /** * The hardware protected indicator for the key. */ private boolean hardwareProtected; /** * Creates a {@link CreateOctKeyOptions} with {@code name} as name of the AES key. * * @param name The name of the key. */ public CreateOctKeyOptions(String name) { super(name, KeyType.OCT); } /** * Get the key size in bits. * * @return The key size in bits. */ /** * Set the key size in bits. * * @param keySize The key size to set. * * @return The updated {@link CreateOctKeyOptions} object. */ public CreateOctKeyOptions setKeySize(Integer keySize) { this.keySize = keySize; return this; } /** * Set the key operations. * * @param keyOperations The key operations to set. * * @return The updated {@link CreateOctKeyOptions} object. */ @Override public CreateOctKeyOptions setKeyOperations(KeyOperation... keyOperations) { super.setKeyOperations(keyOperations); return this; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set. * * @return The updated {@link CreateOctKeyOptions} object. */ @Override public CreateOctKeyOptions setNotBefore(OffsetDateTime notBefore) { super.setNotBefore(notBefore); return this; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expiresOn The expiry time to set. for the key. * * @return The updated {@link CreateOctKeyOptions} object. */ @Override public CreateOctKeyOptions setExpiresOn(OffsetDateTime expiresOn) { super.setExpiresOn(expiresOn); return this; } /** * Set the tags to be associated with the key. * * @param tags The tags to set. * * @return The updated {@link CreateOctKeyOptions} object. */ @Override public CreateOctKeyOptions setTags(Map<String, String> tags) { super.setTags(tags); return this; } /** * Set a value that indicates if the key is enabled. * * @param enabled The enabled value to set. * * @return The updated {@link CreateOctKeyOptions} object. */ public CreateOctKeyOptions setEnabled(Boolean enabled) { super.setEnabled(enabled); return this; } /** * Set whether the key being created is of HSM type or not. * * @param hardwareProtected The HSM value to set. * * @return The updated {@link CreateOctKeyOptions} object. */ public CreateOctKeyOptions setHardwareProtected(Boolean hardwareProtected) { this.hardwareProtected = hardwareProtected; KeyType keyType = hardwareProtected ? KeyType.OCT_HSM : KeyType.OCT; setKeyType(keyType); return this; } /** * Get the HSM value of the key being created. * * @return the HSM value. */ public Boolean isHardwareProtected() { return this.hardwareProtected; } }
class CreateOctKeyOptions extends CreateKeyOptions { /** * The AES key size. */ private Integer keySize; /** * The hardware protected indicator for the key. */ private boolean hardwareProtected; /** * Creates a {@link CreateOctKeyOptions} with {@code name} as name of the AES key. * * @param name The name of the key. */ public CreateOctKeyOptions(String name) { super(name, KeyType.OCT); } /** * Set the key operations. * * @param keyOperations The key operations to set. * * @return The updated {@link CreateOctKeyOptions} object. */ @Override public CreateOctKeyOptions setKeyOperations(KeyOperation... keyOperations) { super.setKeyOperations(keyOperations); return this; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set. * * @return The updated {@link CreateOctKeyOptions} object. */ @Override public CreateOctKeyOptions setNotBefore(OffsetDateTime notBefore) { super.setNotBefore(notBefore); return this; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expiresOn The expiry time to set. for the key. * * @return The updated {@link CreateOctKeyOptions} object. */ @Override public CreateOctKeyOptions setExpiresOn(OffsetDateTime expiresOn) { super.setExpiresOn(expiresOn); return this; } /** * Set the tags to be associated with the key. * * @param tags The tags to set. * * @return The updated {@link CreateOctKeyOptions} object. */ @Override public CreateOctKeyOptions setTags(Map<String, String> tags) { super.setTags(tags); return this; } /** * Set a value that indicates if the key is enabled. * * @param enabled The enabled value to set. * * @return The updated {@link CreateOctKeyOptions} object. */ public CreateOctKeyOptions setEnabled(Boolean enabled) { super.setEnabled(enabled); return this; } /** * Set the key size in bits. * * @param keySize The key size to set. * * @return The updated {@link CreateOctKeyOptions} object. */ public CreateOctKeyOptions setKeySize(Integer keySize) { this.keySize = keySize; return this; } /** * Get the key size in bits. * * @return The key size in bits. */ /** * Set whether the key being created is of HSM type or not. * * @param hardwareProtected The HSM value to set. * * @return The updated {@link CreateOctKeyOptions} object. */ public CreateOctKeyOptions setHardwareProtected(Boolean hardwareProtected) { this.hardwareProtected = hardwareProtected; KeyType keyType = hardwareProtected ? KeyType.OCT_HSM : KeyType.OCT; setKeyType(keyType); return this; } /** * Get the HSM value of the key being created. * * @return the HSM value. */ public Boolean isHardwareProtected() { return this.hardwareProtected; } }
Might consider naming this class specific to AES. We may have others in the future (no idea) that could be symmetric. The other clients are specific to a class of algorithms as well.
private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new SymmetricKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } }
new SymmetricKeyCryptographyClient(this.key, this.cryptographyServiceClient);
private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new AesKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when an Azure Key Vault key identifier was not provided when creating this " + "client")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plainText The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plainText) { return encrypt(new EncryptOptions(algorithm, plainText, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptOptions The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptOptions encryptOptions) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); try { return withContext(context -> encrypt(encryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptOptions, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(new DecryptOptions(algorithm, cipherText, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptOptions The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptOptions decryptOptions) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); try { return withContext(context -> decrypt(decryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptOptions, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final HttpPipeline pipeline; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.pipeline = pipeline; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = jsonWebKey.getId(); this.pipeline = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when in operating local-only mode")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(new EncryptParameters(algorithm, plaintext, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptParameters The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptParameters encryptParameters) { Objects.requireNonNull(encryptParameters, "'encryptParameters' cannot be null."); try { return withContext(context -> encrypt(encryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptParameters encryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptParameters, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { return decrypt(new DecryptParameters(algorithm, ciphertext, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptParameters The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptParameters decryptParameters) { Objects.requireNonNull(decryptParameters, "'decryptParameters' cannot be null."); try { return withContext(context -> decrypt(decryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptParameters decryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptParameters, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
Speaking of exceptions (not specific to this line, but in general): for hybrid, are you swallowing (or even logging) cryptographic exceptions from the local crypto client and calling remote?
private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } }
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e));
private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new SymmetricKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when an Azure Key Vault key identifier was not provided when creating this " + "client")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plainText The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plainText) { return encrypt(new EncryptOptions(algorithm, plainText, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptOptions The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptOptions encryptOptions) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); try { return withContext(context -> encrypt(encryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptOptions, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(new DecryptOptions(algorithm, cipherText, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptOptions The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptOptions decryptOptions) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); try { return withContext(context -> decrypt(decryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptOptions, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final HttpPipeline pipeline; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.pipeline = pipeline; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = jsonWebKey.getId(); this.pipeline = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new AesKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when in operating local-only mode")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(new EncryptParameters(algorithm, plaintext, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptParameters The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptParameters encryptParameters) { Objects.requireNonNull(encryptParameters, "'encryptParameters' cannot be null."); try { return withContext(context -> encrypt(encryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptParameters encryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptParameters, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { return decrypt(new DecryptParameters(algorithm, ciphertext, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptParameters The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptParameters decryptParameters) { Objects.requireNonNull(decryptParameters, "'decryptParameters' cannot be null."); try { return withContext(context -> decrypt(decryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptParameters decryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptParameters, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
Curious: why defer a call to get something in memory? /cc @g2vinay
Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); }
return Mono.defer(() -> Mono.just(this.keyId));
Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new SymmetricKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when an Azure Key Vault key identifier was not provided when creating this " + "client")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plainText The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plainText) { return encrypt(new EncryptOptions(algorithm, plainText, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptOptions The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptOptions encryptOptions) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); try { return withContext(context -> encrypt(encryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptOptions, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(new DecryptOptions(algorithm, cipherText, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptOptions The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptOptions decryptOptions) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); try { return withContext(context -> decrypt(decryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptOptions, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final HttpPipeline pipeline; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.pipeline = pipeline; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = jsonWebKey.getId(); this.pipeline = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new AesKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when in operating local-only mode")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(new EncryptParameters(algorithm, plaintext, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptParameters The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptParameters encryptParameters) { Objects.requireNonNull(encryptParameters, "'encryptParameters' cannot be null."); try { return withContext(context -> encrypt(encryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptParameters encryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptParameters, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { return decrypt(new DecryptParameters(algorithm, ciphertext, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptParameters The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptParameters decryptParameters) { Objects.requireNonNull(decryptParameters, "'decryptParameters' cannot be null."); try { return withContext(context -> decrypt(decryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptParameters decryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptParameters, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
As mentioned in another comment, the keyId could be extracted from teh JWK - .NET does this - which means you wouldn't want this check. You could still have a keyId (kid) but that doesn't imply anything on its own.
public CryptographyAsyncClient buildAsyncClient() { if (jsonWebKey == null) { if (Strings.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalStateException( "An Azure Key Vault key identifier is required to build the cryptography client if a JSON Web Key" + " is not provided.")); } CryptographyServiceVersion serviceVersion = version != null ? version : CryptographyServiceVersion.getLatest(); if (pipeline != null) { return new CryptographyAsyncClient(keyId, pipeline, serviceVersion); } if (credential == null) { throw logger.logExceptionAsError(new IllegalStateException( "Azure Key Vault credentials are required to build the cryptography client if a JSON Web Key is not" + " provided.")); } HttpPipeline pipeline = setupPipeline(); return new CryptographyAsyncClient(keyId, pipeline, serviceVersion); } else if (!Strings.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalStateException( "An Azure Key Vault key identifier must not be provided in conjunction with a JSON Web Key.")); } else { return new CryptographyAsyncClient(jsonWebKey); } }
} else if (!Strings.isNullOrEmpty(keyId)) {
public CryptographyAsyncClient buildAsyncClient() { if (jsonWebKey == null) { if (Strings.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalStateException( "An Azure Key Vault key identifier is required to build the cryptography client if a JSON Web Key" + " is not provided.")); } CryptographyServiceVersion serviceVersion = version != null ? version : CryptographyServiceVersion.getLatest(); if (pipeline != null) { return new CryptographyAsyncClient(keyId, pipeline, serviceVersion); } if (credential == null) { throw logger.logExceptionAsError(new IllegalStateException( "Azure Key Vault credentials are required to build the cryptography client if a JSON Web Key is not" + " provided.")); } HttpPipeline pipeline = setupPipeline(); return new CryptographyAsyncClient(keyId, pipeline, serviceVersion); } else { return new CryptographyAsyncClient(jsonWebKey); } }
class CryptographyClientBuilder { final List<HttpPipelinePolicy> policies; final Map<String, String> properties; private final ClientLogger logger = new ClientLogger(CryptographyClientBuilder.class); private static final String AZURE_KEY_VAULT_KEYS = "azure-key-vault-keys.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private JsonWebKey jsonWebKey; private TokenCredential credential; private HttpPipeline pipeline; private String keyId; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private Configuration configuration; private CryptographyServiceVersion version; private ClientOptions clientOptions; /** * The constructor with defaults. */ public CryptographyClientBuilder() { retryPolicy = new RetryPolicy(); httpLogOptions = new HttpLogOptions(); policies = new ArrayList<>(); properties = CoreUtils.getProperties(AZURE_KEY_VAULT_KEYS); } /** * Creates a {@link CryptographyClient} based on options set in the builder. Every time {@code buildClient()} is * called, a new instance of {@link CryptographyClient} is created. * * <p>If {@link CryptographyClientBuilder * settings are ignored.</p> * * <p>If {@link CryptographyClientBuilder * {@link CryptographyClientBuilder * {@link CryptographyClient client}. All other builder settings are ignored. If {@code pipeline} is not set, * then an {@link CryptographyClientBuilder * {@link CryptographyClientBuilder * {@link CryptographyClient client}.</p> * * @return A {@link CryptographyClient} with the options set from the builder. * * @throws IllegalStateException If {@link CryptographyClientBuilder * {@link CryptographyClientBuilder */ public CryptographyClient buildClient() { return new CryptographyClient(buildAsyncClient()); } /** * Creates a {@link CryptographyAsyncClient} based on options set in the builder. Every time * {@link * * <p>If {@link CryptographyClientBuilder * settings are ignored.</p> * * <p>If {@link CryptographyClientBuilder * {@link CryptographyClientBuilder * {@link CryptographyAsyncClient async client}. All other builder settings are ignored. If {@code pipeline} is * not set, then an {@link CryptographyClientBuilder * {@link CryptographyClientBuilder * {@link CryptographyAsyncClient async client}.</p> * * @return A {@link CryptographyAsyncClient} with the options set from the builder. * * @throws IllegalStateException If {@link CryptographyClientBuilder * {@link CryptographyClientBuilder */ HttpPipeline setupPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = clientOptions == null ? httpLogOptions.getApplicationId() : clientOptions.getApplicationId(); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(this.policies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } TokenCredential getCredential() { return credential; } HttpPipeline getPipeline() { return pipeline; } CryptographyServiceVersion getServiceVersion() { return version; } /** * Sets the Azure Key Vault key identifier of the JSON Web Key to be used for cryptography operations. * * @param keyId The Azure Key Vault key identifier of the JSON Web Key stored in the key vault. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If {@code keyId} is {@code null}. */ public CryptographyClientBuilder keyIdentifier(String keyId) { if (keyId == null) { throw logger.logExceptionAsError(new NullPointerException("'keyId' cannot be null.")); } this.keyId = keyId; return this; } /** * Sets the credential to use when authenticating HTTP requests. * * @param credential The credential to use for authenticating HTTP requests. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If {@code credential} is {@code null}. */ public CryptographyClientBuilder credential(TokenCredential credential) { if (credential == null) { throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); } this.credential = credential; return this; } /** * Sets the {@link JsonWebKey} to be used for local cryptography operations. * * <p>If {@code jsonWebKey} is provided, then all other builder settings are ignored.</p> * * @param jsonWebKey The JSON Web Key to be used for local cryptography operations. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If {@code jsonWebKey} is {@code null}. */ public CryptographyClientBuilder jsonWebKey(JsonWebKey jsonWebKey) { if (jsonWebKey == null) { throw logger.logExceptionAsError(new NullPointerException("'jsonWebKey' must not be null.")); } this.jsonWebKey = jsonWebKey; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after the client required policies. * * @param policy The {@link HttpPipelinePolicy policy} to be added. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If {@code policy} is {@code null}. */ public CryptographyClientBuilder addPolicy(HttpPipelinePolicy policy) { if (policy == null) { throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } policies.add(policy); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If {@code client} is {@code null}. */ public CryptographyClientBuilder httpClient(HttpClient client) { if (client == null) { throw logger.logExceptionAsError(new NullPointerException("'client' cannot be null.")); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from * {@link CryptographyClientBuilder * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If the specified {@code pipeline} is null. */ public CryptographyClientBuilder pipeline(HttpPipeline pipeline) { if (pipeline == null) { throw logger.logExceptionAsError(new NullPointerException("'pipeline' cannot be null.")); } this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the * {@link Configuration * bypass using configuration settings during construction. * * @param configuration The configuration store used to get configuration details. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link CryptographyServiceVersion} 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 CryptographyServiceVersion} of the service to be used when making requests. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder serviceVersion(CryptographyServiceVersion version) { this.version = version; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. The default retry policy will be used in * the pipeline, if not provided. * * @param retryPolicy User's {@link RetryPolicy} applied to each request. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If the specified {@code retryPolicy} is null. */ public CryptographyClientBuilder retryPolicy(RetryPolicy retryPolicy) { if (retryPolicy == null) { throw logger.logExceptionAsError(new NullPointerException("'retryPolicy' cannot be null.")); } this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * Telemetry policy</a> * * @param clientOptions The {@link ClientOptions} to be set on the client. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } }
class CryptographyClientBuilder { private final ClientLogger logger = new ClientLogger(CryptographyClientBuilder.class); private static final String AZURE_KEY_VAULT_KEYS = "azure-key-vault-keys.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final List<HttpPipelinePolicy> perCallPolicies; private final List<HttpPipelinePolicy> perRetryPolicies; private final Map<String, String> properties; private ClientOptions clientOptions; private Configuration configuration; private CryptographyServiceVersion version; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private JsonWebKey jsonWebKey; private RetryPolicy retryPolicy; private String keyId; private TokenCredential credential; /** * The constructor with defaults. */ public CryptographyClientBuilder() { httpLogOptions = new HttpLogOptions(); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); properties = CoreUtils.getProperties(AZURE_KEY_VAULT_KEYS); retryPolicy = new RetryPolicy(); } /** * Creates a {@link CryptographyClient} based on options set in the builder. Every time {@code buildClient()} is * called, a new instance of {@link CryptographyClient} is created. * * <p>If {@link CryptographyClientBuilder * settings are ignored.</p> * * <p>If {@link CryptographyClientBuilder * {@link CryptographyClientBuilder * {@link CryptographyClient client}. All other builder settings are ignored. If {@code pipeline} is not set, * then an {@link CryptographyClientBuilder * {@link CryptographyClientBuilder * {@link CryptographyClient client}.</p> * * @return A {@link CryptographyClient} with the options set from the builder. * * @throws IllegalStateException If {@link CryptographyClientBuilder * {@link CryptographyClientBuilder */ public CryptographyClient buildClient() { return new CryptographyClient(buildAsyncClient()); } /** * Creates a {@link CryptographyAsyncClient} based on options set in the builder. Every time * {@link * * <p>If {@link CryptographyClientBuilder * settings are ignored.</p> * * <p>If {@link CryptographyClientBuilder * {@link CryptographyClientBuilder * {@link CryptographyAsyncClient async client}. All other builder settings are ignored. If {@code pipeline} is * not set, then an {@link CryptographyClientBuilder * {@link CryptographyClientBuilder * {@link CryptographyAsyncClient async client}.</p> * * @return A {@link CryptographyAsyncClient} with the options set from the builder. * * @throws IllegalStateException If {@link CryptographyClientBuilder * {@link CryptographyClientBuilder */ HttpPipeline setupPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration)); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } TokenCredential getCredential() { return credential; } HttpPipeline getPipeline() { return pipeline; } CryptographyServiceVersion getServiceVersion() { return version; } /** * Sets the Azure Key Vault key identifier of the JSON Web Key to be used for cryptography operations. * * @param keyId The Azure Key Vault key identifier of the JSON Web Key stored in the key vault. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If {@code keyId} is {@code null}. */ public CryptographyClientBuilder keyIdentifier(String keyId) { if (keyId == null) { throw logger.logExceptionAsError(new NullPointerException("'keyId' cannot be null.")); } this.keyId = keyId; return this; } /** * Sets the credential to use when authenticating HTTP requests. * * @param credential The credential to use for authenticating HTTP requests. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If {@code credential} is {@code null}. */ public CryptographyClientBuilder credential(TokenCredential credential) { if (credential == null) { throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); } this.credential = credential; return this; } /** * Sets the {@link JsonWebKey} to be used for local cryptography operations. * * <p>If {@code jsonWebKey} is provided, then all other builder settings are ignored.</p> * * @param jsonWebKey The JSON Web Key to be used for local cryptography operations. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If {@code jsonWebKey} is {@code null}. */ public CryptographyClientBuilder jsonWebKey(JsonWebKey jsonWebKey) { if (jsonWebKey == null) { throw logger.logExceptionAsError(new NullPointerException("'jsonWebKey' must not be null.")); } this.jsonWebKey = jsonWebKey; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after the client required policies. * * @param policy The {@link HttpPipelinePolicy policy} to be added. * * @return The updated {@link CryptographyClientBuilder} object. * * @throws NullPointerException If {@code policy} is {@code null}. */ public CryptographyClientBuilder addPolicy(HttpPipelinePolicy policy) { if (policy == null) { throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder httpClient(HttpClient client) { this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from * {@link CryptographyClientBuilder * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the * {@link Configuration * bypass using configuration settings during construction. * * @param configuration The configuration store used to get configuration details. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link CryptographyServiceVersion} 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 CryptographyServiceVersion} of the service to be used when making requests. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder serviceVersion(CryptographyServiceVersion version) { this.version = version; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. The default retry policy will be used in * the pipeline, if not provided. * * @param retryPolicy User's {@link RetryPolicy} applied to each request. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions * {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https: * Telemetry policy</a> * * @param clientOptions The {@link ClientOptions} to be set on the client. * * @return The updated {@link CryptographyClientBuilder} object. */ public CryptographyClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } }
I don't think so. If the key is available locally and is valid the client will always try to perform the operation locally. Might want to change that behavior to what you suggested in a future PR.
private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } }
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e));
private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new SymmetricKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when an Azure Key Vault key identifier was not provided when creating this " + "client")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plainText The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plainText) { return encrypt(new EncryptOptions(algorithm, plainText, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptOptions The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptOptions encryptOptions) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); try { return withContext(context -> encrypt(encryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptOptions, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(new DecryptOptions(algorithm, cipherText, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptOptions The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptOptions decryptOptions) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); try { return withContext(context -> decrypt(decryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptOptions, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final HttpPipeline pipeline; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.pipeline = pipeline; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = jsonWebKey.getId(); this.pipeline = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new AesKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when in operating local-only mode")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(new EncryptParameters(algorithm, plaintext, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptParameters The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptParameters encryptParameters) { Objects.requireNonNull(encryptParameters, "'encryptParameters' cannot be null."); try { return withContext(context -> encrypt(encryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptParameters encryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptParameters, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { return decrypt(new DecryptParameters(algorithm, ciphertext, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptParameters The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptParameters decryptParameters) { Objects.requireNonNull(decryptParameters, "'decryptParameters' cannot be null."); try { return withContext(context -> decrypt(decryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptParameters decryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptParameters, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
Please open an issue. That is actually how it should work across SDKs. Only obvious input exceptions should throw and not forward to the service.
private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } }
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e));
private void unpackAndValidateId(String keyId) { if (CoreUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); this.keyCollection = (tokens.length >= 2 ? tokens[1] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key endpoint in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key name in key identifier is invalid.")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError( new IllegalArgumentException("Key version in key identifier is invalid.")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new SymmetricKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when an Azure Key Vault key identifier was not provided when creating this " + "client")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plainText The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plainText) { return encrypt(new EncryptOptions(algorithm, plainText, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting * the specified {@code plainText}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptOptions The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plainText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptOptions encryptOptions) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); try { return withContext(context -> encrypt(encryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptOptions, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(new DecryptOptions(algorithm, cipherText, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptOptions The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code cipherText} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptOptions decryptOptions) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); try { return withContext(context -> decrypt(decryptOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptOptions, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptOptions, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; JsonWebKey key; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private final CryptographyService service; private final HttpPipeline pipeline; private final String keyId; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private String keyCollection; /** * Creates a {@link CryptographyAsyncClient} that uses a given {@link HttpPipeline pipeline} to service requests. * * @param keyId The Azure Key Vault key identifier to use for cryptography operations. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); this.keyId = keyId; this.pipeline = pipeline; this.service = RestProxy.create(CryptographyService.class, pipeline); this.cryptographyServiceClient = new CryptographyServiceClient(keyId, service, version); this.key = null; } /** * Creates a {@link CryptographyAsyncClient} that uses a {@link JsonWebKey} to perform local cryptography * operations. * * @param jsonWebKey The {@link JsonWebKey} to use for local cryptography operations. */ CryptographyAsyncClient(JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The JSON Web Key is required."); if (!jsonWebKey.isValid()) { throw new IllegalArgumentException("The JSON Web Key is not valid."); } if (jsonWebKey.getKeyOps() == null) { throw new IllegalArgumentException("The JSON Web Key's key operations property is not configured."); } if (jsonWebKey.getKeyType() == null) { throw new IllegalArgumentException("The JSON Web Key's key type property is not configured."); } this.key = jsonWebKey; this.keyId = jsonWebKey.getId(); this.pipeline = null; this.service = null; this.cryptographyServiceClient = null; initializeCryptoClients(); } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { this.localKeyCryptographyClient = new RsaKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { this.localKeyCryptographyClient = new EcKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else if (key.getKeyType().equals(OCT) || key.getKeyType().equals(OCT_HSM)) { this.localKeyCryptographyClient = new AesKeyCryptographyClient(this.key, this.cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The JSON Web Key type: %s is not supported.", this.key.getKeyType().toString()))); } } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ HttpPipeline getHttpPipeline() { return this.pipeline; } Mono<String> getKeyId() { return Mono.defer(() -> Mono.just(this.keyId)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey() { try { return getKeyWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission for non-local operations. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response * requested {@link KeyVaultKey key}. * * @throws ResourceNotFoundException When the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse() { try { return withContext(this::getKeyWithResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) { if (cryptographyServiceClient != null) { return cryptographyServiceClient.getKey(context); } else { throw logger.logExceptionAsError(new UnsupportedOperationException( "Operation not supported when in operating local-only mode")); } } Mono<JsonWebKey> getSecretKey() { try { return withContext(context -> cryptographyServiceClient.getSecretKey(context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(new EncryptParameters(algorithm, plaintext, null, null), null); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports * a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys, the * public portion of the key is used for encryption. This operation requires the {@code keys/encrypt} permission * for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt * * @param encryptParameters The parameters to use in the encryption operation. * * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult * contains the encrypted content. * * @throws NullPointerException If {@code algorithm} or {@code plaintext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for encryption. * @throws UnsupportedOperationException If the encrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<EncryptResult> encrypt(EncryptParameters encryptParameters) { Objects.requireNonNull(encryptParameters, "'encryptParameters' cannot be null."); try { return withContext(context -> encrypt(encryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<EncryptResult> encrypt(EncryptParameters encryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.encrypt(encryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Encrypt operation is missing permission/not supported for key with id: %s", key.getId())))); } return localKeyCryptographyClient.encryptAsync(encryptParameters, context, key); }); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { return decrypt(new DecryptParameters(algorithm, ciphertext, null, null, null)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm * to be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires * the {@code keys/decrypt} permission for non-local operations. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting * the specified encrypted content. Possible values for asymmetric keys include: * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt * * @param decryptParameters The parameters to use in the decryption operation. * * @return A {@link Mono} containing the decrypted blob. * * @throws NullPointerException If {@code algorithm} or {@code ciphertext} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for decryption. * @throws UnsupportedOperationException If the decrypt operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DecryptResult> decrypt(DecryptParameters decryptParameters) { Objects.requireNonNull(decryptParameters, "'decryptParameters' cannot be null."); try { return withContext(context -> decrypt(decryptParameters, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<DecryptResult> decrypt(DecryptParameters decryptParameters, Context context) { return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.decrypt(decryptParameters, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Decrypt operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.decryptAsync(decryptParameters, context, key); }); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code digest} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { try { return withContext(context -> sign(algorithm, digest, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); }); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature. This operation * requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code digest} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { try { return withContext(context -> verify(algorithm, digest, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", key.getId())))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); }); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the {@code keys/wrapKey} permission for non-local * operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. * * @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult * contains the wrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code key} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the wrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { try { return withContext(context -> wrapKey(algorithm, key, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Wrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); }); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation * is the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This * operation requires the {@code keys/unwrapKey} permission for non-local operations. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * * @return A {@link Mono} containing an {@link UnwrapResult} whose {@link UnwrapResult * key} contains the unwrapped key result. * * @throws NullPointerException If {@code algorithm} or {@code encryptedKey} are {@code null}. * @throws ResourceNotFoundException If the key cannot be found for wrap operation. * @throws UnsupportedOperationException If the unwrap operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { try { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Unwrap Key operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the {@code keys/sign} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult * the created signature. * * @throws NullPointerException If {@code algorithm} or {@code data} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for signing. * @throws UnsupportedOperationException If the sign operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { try { return withContext(context -> signData(algorithm, data, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Sign Operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); }); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. In case of asymmetric keys public portion of the key is used to verify the signature. * This operation requires the {@code keys/verify} permission for non-local operations. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * * @return A {@link Mono} containing a {@link VerifyResult} * {@link VerifyResult * * @throws NullPointerException If {@code algorithm}, {@code data} or {@code signature} is {@code null}. * @throws ResourceNotFoundException If the key cannot be found for verifying. * @throws UnsupportedOperationException If the verify operation is not supported or configured on the key. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { try { return withContext(context -> verifyData(algorithm, data, signature, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "Verify operation is not allowed for key with id: %s", this.key.getId())))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); }); } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (key == null && keyCollection != null); boolean keyNotValid = (key != null && !key.isValid()); if (keyNotAvailable || keyNotValid) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jsonWebKey -> { key = (jsonWebKey); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } else { return getKey().map(keyVaultKey -> { key = (keyVaultKey.getKey()); if (key.isValid()) { initializeCryptoClients(); return true; } else { return false; } }); } } else { return Mono.defer(() -> Mono.just(true)); } } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } void setCryptographyServiceClient(CryptographyServiceClient serviceClient) { this.cryptographyServiceClient = serviceClient; } }
This can easily be part of the proxy and all generic error codes can\should be handle by Rest proxy unless the library requires special handling - 401, 400, 503, 409 etc. Let me know if this is supported else will create an issue for this. #Pending
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } }
.onErrorMap(Utils::mapException);
return monoError(logger, new NullPointerException("'name' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final SerializerAdapter serializerAdapter; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .serializerAdapter(serializerAdapter).buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); } /** * List repositories. * * @return list of repositories. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint); } }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, String endpoint, String version) { this.httpPipeline = httpPipeline; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List all the repository names in this registry. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of repository names. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the repository (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { } /** * Delete the repository identified by 'name'. * * @param name Name of the image (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, endpoint, apiVersion); } }
Generally we've allowed context to be null in the past, have you found this causes an error if it is null? #Resolved
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } }
return monoError(logger, new NullPointerException("'context' cannot be null."));
return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final SerializerAdapter serializerAdapter; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String version) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .serializerAdapter(serializerAdapter).buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List repositories. * * @return list of repositories. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, apiVersion); } }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, String endpoint, String version) { this.httpPipeline = httpPipeline; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List all the repository names in this registry. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of repository names. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the repository (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the image (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, endpoint, apiVersion); } }
Generally, we don't want to provide client side validation such as this. Normally, this will go to the service and return an error. If we do keep this I would go with `IllegalArgumentException` #Pending
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } }
return monoError(logger, new NullPointerException("'name' cannot be null."));
return monoError(logger, new NullPointerException("'name' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final SerializerAdapter serializerAdapter; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String version) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .serializerAdapter(serializerAdapter).buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List repositories. * * @return list of repositories. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, apiVersion); } }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, String endpoint, String version) { this.httpPipeline = httpPipeline; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List all the repository names in this registry. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of repository names. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the repository (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { } /** * Delete the repository identified by 'name'. * * @param name Name of the image (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, endpoint, apiVersion); } }
Should document that this will make a second network call if the tagOrDigest contains `:`. Additionally, this doesn't need to be put into a defer as all network calls are implicitly deferred until subscribed to #Resolved
Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<String> getTagMono = Mono.defer( () -> tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest())); return getTagMono .flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } }
() -> tagOrDigest.contains(":")
return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializerAdapter) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } /** * Delete repository. * * @param context Context associated with the operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { if (context == null) { } /** * Delete repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().map(Response::getValue); } /** * Delete registry artifact. * * @param digest Digest name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Delete tag. * * @param tag tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().map(Response::getValue); } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<String> getTagMono = Mono.defer( () -> tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest())); return getTagMono .flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).map(Response::getValue); } /** * List registry artifacts based of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List manifests of a repository. * * @param options the options associated with the list registy operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).map(Response::getValue); } /** * List tags of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value) .flatMap((Response<Void> res) -> Mono.empty()); } }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().flatMap(FluxUtil::toMono); } /** * Delete registry artifact. * * @param digest the digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest).flatMap(FluxUtil::toMono); } /** * Delete tag. * * @param tag tag to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag tag to delete * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag).flatMap(FluxUtil::toMono); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given repository was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { Mono<String> getTagMono = tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest()); return getTagMono .flatMap(digest -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, digest)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).flatMap(FluxUtil::toMono); } /** * List registry artifacts of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List registry artifacts of a repository. * * @param options the options associated with the list registry operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).flatMap(FluxUtil::toMono); } /** * List tags of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value).flatMap(FluxUtil::toMono); } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value).flatMap(FluxUtil::toMono); } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value).flatMap(FluxUtil::toMono); } }
Add an `@throws` of IllegalArgumentException` if `endpoint` isn't a valid URL #Resolved
public ContainerRepositoryClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; }
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
public ContainerRepositoryClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; }
class ContainerRepositoryClientBuilder { private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-containers-containerregistry.properties"); private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion"); private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private String endpoint; private HttpClient httpClient; private TokenCredential credential; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions; private SerializerAdapter serializerAdapter; private RetryPolicy retryPolicy; private String repository; private ContainerRegistryServiceVersion version; /** * Sets Registry login URL. * * @param endpoint the endpoint value. * @return the ContainerRepositoryClientBuilder. */ /** * Sets repository name. * * @param repository name * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder repository(String repository) { this.repository = Objects.requireNonNull(repository, "'repository' cannot be null."); return this; } /** * Sets Registry login URL. * * @param credential the credential to use to access registry. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder credential(TokenCredential credential) { this.credential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets The HTTP httpPipeline to send requests through. * * @param httpPipeline the httpPipeline value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.verbose("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the service version that will be targeted by the client. * * @param version the service version to target. * @return the ContainerRegistryBuilder. */ public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) { this.version = version; return this; } /** * Sets The HTTP client used to send the request. * * @param httpClient the httpClient value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { logger.verbose("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The {@link ClientOptions}. * @return The updated {@code TableClientBuilder}. */ public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets The configuration store that is used during construction of the service client. * * @param configuration the configuration value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets The logging configuration for HTTP requests and responses. * * @param httpLogOptions the httpLogOptions value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null."); return this; } /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a custom Http httpPipeline policy. * * @param customPolicy The custom Http httpPipeline policy to add. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null."); if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(customPolicy); } else { perRetryPolicies.add(customPolicy); } return this; } /** * Builds an instance of ContainerRegistryImpl with the provided parameters. * * @return an instance of ContainerRegistryImpl. */ public ContainerRepositoryAsyncClient buildAsyncClient() { if (serializerAdapter == null) { this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); } ContainerRegistryServiceVersion serviceVersion = (version != null) ? version : ContainerRegistryServiceVersion.getLatest(); if (httpPipeline == null) { this.httpPipeline = createHttpPipeline(); } ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, serviceVersion.getVersion()); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); List<HttpHeader> httpHeaderList = new ArrayList<>(); if (clientOptions != null) { clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); } policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.add(new CookiePolicy()); policies.add(new AddDatePolicy()); policies.addAll(this.perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); if (credential != null) { policies.add(new ContainerRegistryCredentialsPolicy( credential, endpoint, new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(), serializerAdapter )); } HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return httpPipeline; } /** * Builds an instance of ContainerRegistryClient sync client. * * @return an instance of ContainerRegistryClient. */ public ContainerRepositoryClient buildClient() { return new ContainerRepositoryClient(buildAsyncClient()); } }
class ContainerRepositoryClientBuilder { private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-containers-containerregistry.properties"); private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion"); private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private String endpoint; private HttpClient httpClient; private TokenCredential credential; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions; private SerializerAdapter serializerAdapter; private RetryPolicy retryPolicy; private String repository; private ContainerRegistryServiceVersion version; /** * Sets Registry login URL. * * @throws IllegalArgumentException if endpoint is not a valid URL. * @param endpoint the endpoint value. * @return the ContainerRepositoryClientBuilder. */ /** * Sets repository name. * @param repository non null repository name * * @throws NullPointerException if repository name is null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder repository(String repository) { this.repository = Objects.requireNonNull(repository, "'repository' cannot be null."); return this; } /** * Sets Registry login URL. * * @param credential the credential to use to access registry. * @throws NullPointerException if credential is null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder credential(TokenCredential credential) { this.credential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets The HTTP httpPipeline to send requests through. * * @param httpPipeline the httpPipeline value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the service version that will be targeted by the client. * * @param version the service version to target. * @return the ContainerRegistryBuilder. */ public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) { this.version = version; return this; } /** * Sets The HTTP client used to send the request. * * @param httpClient the httpClient value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The {@link ClientOptions}. * @return The updated {@code TableClientBuilder}. */ public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets The configuration store that is used during construction of the service client. * * @param configuration the configuration value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets The logging configuration for HTTP requests and responses. * * @param httpLogOptions the httpLogOptions value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a custom Http httpPipeline policy. * * @param customPolicy The custom Http httpPipeline policy to add. * @throws NullPointerException custom policy can't be null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(customPolicy); } else { perRetryPolicies.add(customPolicy); } return this; } /** * Builds an instance of ContainerRegistryImpl with the provided parameters. * * @return an instance of ContainerRegistryImpl. */ public ContainerRepositoryAsyncClient buildAsyncClient() { if (serializerAdapter == null) { this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); } ContainerRegistryServiceVersion serviceVersion = (version != null) ? version : ContainerRegistryServiceVersion.getLatest(); HttpPipeline pipeline = getHttpPipeline(); ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, pipeline, endpoint, serviceVersion.getVersion()); return client; } private HttpPipeline getHttpPipeline() { if (httpPipeline != null) { return httpPipeline; } Objects.requireNonNull(credential, "'credential' cannot be null."); return Utils.buildHttpPipeline( this.clientOptions, this.httpLogOptions, this.configuration, this.retryPolicy, this.credential, this.perCallPolicies, this.perRetryPolicies, this.httpClient, this.endpoint); } /** * Builds an instance of ContainerRegistryClient sync client. * * @return an instance of ContainerRegistryClient. */ public ContainerRepositoryClient buildClient() { return new ContainerRepositoryClient(buildAsyncClient()); } }
Document that `repository` cannot be null #Resolved
public ContainerRepositoryClientBuilder repository(String repository) { this.repository = Objects.requireNonNull(repository, "'repository' cannot be null."); return this; }
this.repository = Objects.requireNonNull(repository,
public ContainerRepositoryClientBuilder repository(String repository) { this.repository = Objects.requireNonNull(repository, "'repository' cannot be null."); return this; }
class ContainerRepositoryClientBuilder { private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-containers-containerregistry.properties"); private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion"); private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private String endpoint; private HttpClient httpClient; private TokenCredential credential; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions; private SerializerAdapter serializerAdapter; private RetryPolicy retryPolicy; private String repository; private ContainerRegistryServiceVersion version; /** * Sets Registry login URL. * * @param endpoint the endpoint value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets repository name. * * @param repository name * @return the ContainerRepositoryClientBuilder. */ /** * Sets Registry login URL. * * @param credential the credential to use to access registry. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder credential(TokenCredential credential) { this.credential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets The HTTP httpPipeline to send requests through. * * @param httpPipeline the httpPipeline value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.verbose("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the service version that will be targeted by the client. * * @param version the service version to target. * @return the ContainerRegistryBuilder. */ public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) { this.version = version; return this; } /** * Sets The HTTP client used to send the request. * * @param httpClient the httpClient value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { logger.verbose("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The {@link ClientOptions}. * @return The updated {@code TableClientBuilder}. */ public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets The configuration store that is used during construction of the service client. * * @param configuration the configuration value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets The logging configuration for HTTP requests and responses. * * @param httpLogOptions the httpLogOptions value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null."); return this; } /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a custom Http httpPipeline policy. * * @param customPolicy The custom Http httpPipeline policy to add. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null."); if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(customPolicy); } else { perRetryPolicies.add(customPolicy); } return this; } /** * Builds an instance of ContainerRegistryImpl with the provided parameters. * * @return an instance of ContainerRegistryImpl. */ public ContainerRepositoryAsyncClient buildAsyncClient() { if (serializerAdapter == null) { this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); } ContainerRegistryServiceVersion serviceVersion = (version != null) ? version : ContainerRegistryServiceVersion.getLatest(); if (httpPipeline == null) { this.httpPipeline = createHttpPipeline(); } ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, serviceVersion.getVersion()); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); List<HttpHeader> httpHeaderList = new ArrayList<>(); if (clientOptions != null) { clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); } policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.add(new CookiePolicy()); policies.add(new AddDatePolicy()); policies.addAll(this.perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); if (credential != null) { policies.add(new ContainerRegistryCredentialsPolicy( credential, endpoint, new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(), serializerAdapter )); } HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return httpPipeline; } /** * Builds an instance of ContainerRegistryClient sync client. * * @return an instance of ContainerRegistryClient. */ public ContainerRepositoryClient buildClient() { return new ContainerRepositoryClient(buildAsyncClient()); } }
class ContainerRepositoryClientBuilder { private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-containers-containerregistry.properties"); private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion"); private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private String endpoint; private HttpClient httpClient; private TokenCredential credential; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions; private SerializerAdapter serializerAdapter; private RetryPolicy retryPolicy; private String repository; private ContainerRegistryServiceVersion version; /** * Sets Registry login URL. * * @throws IllegalArgumentException if endpoint is not a valid URL. * @param endpoint the endpoint value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets repository name. * @param repository non null repository name * * @throws NullPointerException if repository name is null. * @return the ContainerRepositoryClientBuilder. */ /** * Sets Registry login URL. * * @param credential the credential to use to access registry. * @throws NullPointerException if credential is null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder credential(TokenCredential credential) { this.credential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets The HTTP httpPipeline to send requests through. * * @param httpPipeline the httpPipeline value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the service version that will be targeted by the client. * * @param version the service version to target. * @return the ContainerRegistryBuilder. */ public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) { this.version = version; return this; } /** * Sets The HTTP client used to send the request. * * @param httpClient the httpClient value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The {@link ClientOptions}. * @return The updated {@code TableClientBuilder}. */ public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets The configuration store that is used during construction of the service client. * * @param configuration the configuration value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets The logging configuration for HTTP requests and responses. * * @param httpLogOptions the httpLogOptions value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a custom Http httpPipeline policy. * * @param customPolicy The custom Http httpPipeline policy to add. * @throws NullPointerException custom policy can't be null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(customPolicy); } else { perRetryPolicies.add(customPolicy); } return this; } /** * Builds an instance of ContainerRegistryImpl with the provided parameters. * * @return an instance of ContainerRegistryImpl. */ public ContainerRepositoryAsyncClient buildAsyncClient() { if (serializerAdapter == null) { this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); } ContainerRegistryServiceVersion serviceVersion = (version != null) ? version : ContainerRegistryServiceVersion.getLatest(); HttpPipeline pipeline = getHttpPipeline(); ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, pipeline, endpoint, serviceVersion.getVersion()); return client; } private HttpPipeline getHttpPipeline() { if (httpPipeline != null) { return httpPipeline; } Objects.requireNonNull(credential, "'credential' cannot be null."); return Utils.buildHttpPipeline( this.clientOptions, this.httpLogOptions, this.configuration, this.retryPolicy, this.credential, this.perCallPolicies, this.perRetryPolicies, this.httpClient, this.endpoint); } /** * Builds an instance of ContainerRegistryClient sync client. * * @return an instance of ContainerRegistryClient. */ public ContainerRepositoryClient buildClient() { return new ContainerRepositoryClient(buildAsyncClient()); } }
HttpLogOptions should be allowed null, if it isn't set it should be ignored #Resolved
public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null."); return this; }
this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null.");
public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; }
class ContainerRepositoryClientBuilder { private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-containers-containerregistry.properties"); private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion"); private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private String endpoint; private HttpClient httpClient; private TokenCredential credential; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions; private SerializerAdapter serializerAdapter; private RetryPolicy retryPolicy; private String repository; private ContainerRegistryServiceVersion version; /** * Sets Registry login URL. * * @param endpoint the endpoint value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets repository name. * * @param repository name * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder repository(String repository) { this.repository = Objects.requireNonNull(repository, "'repository' cannot be null."); return this; } /** * Sets Registry login URL. * * @param credential the credential to use to access registry. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder credential(TokenCredential credential) { this.credential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets The HTTP httpPipeline to send requests through. * * @param httpPipeline the httpPipeline value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.verbose("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the service version that will be targeted by the client. * * @param version the service version to target. * @return the ContainerRegistryBuilder. */ public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) { this.version = version; return this; } /** * Sets The HTTP client used to send the request. * * @param httpClient the httpClient value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { logger.verbose("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The {@link ClientOptions}. * @return The updated {@code TableClientBuilder}. */ public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets The configuration store that is used during construction of the service client. * * @param configuration the configuration value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets The logging configuration for HTTP requests and responses. * * @param httpLogOptions the httpLogOptions value. * @return the ContainerRepositoryClientBuilder. */ /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a custom Http httpPipeline policy. * * @param customPolicy The custom Http httpPipeline policy to add. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null."); if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(customPolicy); } else { perRetryPolicies.add(customPolicy); } return this; } /** * Builds an instance of ContainerRegistryImpl with the provided parameters. * * @return an instance of ContainerRegistryImpl. */ public ContainerRepositoryAsyncClient buildAsyncClient() { if (serializerAdapter == null) { this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); } ContainerRegistryServiceVersion serviceVersion = (version != null) ? version : ContainerRegistryServiceVersion.getLatest(); if (httpPipeline == null) { this.httpPipeline = createHttpPipeline(); } ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, serviceVersion.getVersion()); return client; } private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); List<HttpHeader> httpHeaderList = new ArrayList<>(); if (clientOptions != null) { clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); } policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.add(new CookiePolicy()); policies.add(new AddDatePolicy()); policies.addAll(this.perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); if (credential != null) { policies.add(new ContainerRegistryCredentialsPolicy( credential, endpoint, new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(), serializerAdapter )); } HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return httpPipeline; } /** * Builds an instance of ContainerRegistryClient sync client. * * @return an instance of ContainerRegistryClient. */ public ContainerRepositoryClient buildClient() { return new ContainerRepositoryClient(buildAsyncClient()); } }
class ContainerRepositoryClientBuilder { private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-containers-containerregistry.properties"); private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion"); private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private String endpoint; private HttpClient httpClient; private TokenCredential credential; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions; private SerializerAdapter serializerAdapter; private RetryPolicy retryPolicy; private String repository; private ContainerRegistryServiceVersion version; /** * Sets Registry login URL. * * @throws IllegalArgumentException if endpoint is not a valid URL. * @param endpoint the endpoint value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets repository name. * @param repository non null repository name * * @throws NullPointerException if repository name is null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder repository(String repository) { this.repository = Objects.requireNonNull(repository, "'repository' cannot be null."); return this; } /** * Sets Registry login URL. * * @param credential the credential to use to access registry. * @throws NullPointerException if credential is null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder credential(TokenCredential credential) { this.credential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets The HTTP httpPipeline to send requests through. * * @param httpPipeline the httpPipeline value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the service version that will be targeted by the client. * * @param version the service version to target. * @return the ContainerRegistryBuilder. */ public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) { this.version = version; return this; } /** * Sets The HTTP client used to send the request. * * @param httpClient the httpClient value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The {@link ClientOptions}. * @return The updated {@code TableClientBuilder}. */ public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets The configuration store that is used during construction of the service client. * * @param configuration the configuration value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets The logging configuration for HTTP requests and responses. * * @param httpLogOptions the httpLogOptions value. * @return the ContainerRepositoryClientBuilder. */ /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a custom Http httpPipeline policy. * * @param customPolicy The custom Http httpPipeline policy to add. * @throws NullPointerException custom policy can't be null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(customPolicy); } else { perRetryPolicies.add(customPolicy); } return this; } /** * Builds an instance of ContainerRegistryImpl with the provided parameters. * * @return an instance of ContainerRegistryImpl. */ public ContainerRepositoryAsyncClient buildAsyncClient() { if (serializerAdapter == null) { this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); } ContainerRegistryServiceVersion serviceVersion = (version != null) ? version : ContainerRegistryServiceVersion.getLatest(); HttpPipeline pipeline = getHttpPipeline(); ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, pipeline, endpoint, serviceVersion.getVersion()); return client; } private HttpPipeline getHttpPipeline() { if (httpPipeline != null) { return httpPipeline; } Objects.requireNonNull(credential, "'credential' cannot be null."); return Utils.buildHttpPipeline( this.clientOptions, this.httpLogOptions, this.configuration, this.retryPolicy, this.credential, this.perCallPolicies, this.perRetryPolicies, this.httpClient, this.endpoint); } /** * Builds an instance of ContainerRegistryClient sync client. * * @return an instance of ContainerRegistryClient. */ public ContainerRepositoryClient buildClient() { return new ContainerRepositoryClient(buildAsyncClient()); } }
nit: Don't set the pipeline used in the builder here, make this a local variable if the client builder doesn't have it configured. This could create problems if they want to make another client after this and have applied policy changes. #Resolved
public ContainerRepositoryAsyncClient buildAsyncClient() { if (serializerAdapter == null) { this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); } ContainerRegistryServiceVersion serviceVersion = (version != null) ? version : ContainerRegistryServiceVersion.getLatest(); if (httpPipeline == null) { this.httpPipeline = createHttpPipeline(); } ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, serviceVersion.getVersion()); return client; }
this.httpPipeline = createHttpPipeline();
public ContainerRepositoryAsyncClient buildAsyncClient() { if (serializerAdapter == null) { this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); } ContainerRegistryServiceVersion serviceVersion = (version != null) ? version : ContainerRegistryServiceVersion.getLatest(); HttpPipeline pipeline = getHttpPipeline(); ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, pipeline, endpoint, serviceVersion.getVersion()); return client; }
class ContainerRepositoryClientBuilder { private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-containers-containerregistry.properties"); private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion"); private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private String endpoint; private HttpClient httpClient; private TokenCredential credential; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions; private SerializerAdapter serializerAdapter; private RetryPolicy retryPolicy; private String repository; private ContainerRegistryServiceVersion version; /** * Sets Registry login URL. * * @param endpoint the endpoint value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets repository name. * * @param repository name * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder repository(String repository) { this.repository = Objects.requireNonNull(repository, "'repository' cannot be null."); return this; } /** * Sets Registry login URL. * * @param credential the credential to use to access registry. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder credential(TokenCredential credential) { this.credential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets The HTTP httpPipeline to send requests through. * * @param httpPipeline the httpPipeline value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.verbose("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the service version that will be targeted by the client. * * @param version the service version to target. * @return the ContainerRegistryBuilder. */ public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) { this.version = version; return this; } /** * Sets The HTTP client used to send the request. * * @param httpClient the httpClient value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { logger.verbose("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The {@link ClientOptions}. * @return The updated {@code TableClientBuilder}. */ public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets The configuration store that is used during construction of the service client. * * @param configuration the configuration value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets The logging configuration for HTTP requests and responses. * * @param httpLogOptions the httpLogOptions value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null."); return this; } /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a custom Http httpPipeline policy. * * @param customPolicy The custom Http httpPipeline policy to add. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null."); if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(customPolicy); } else { perRetryPolicies.add(customPolicy); } return this; } /** * Builds an instance of ContainerRegistryImpl with the provided parameters. * * @return an instance of ContainerRegistryImpl. */ private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); List<HttpHeader> httpHeaderList = new ArrayList<>(); if (clientOptions != null) { clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); } policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.add(new CookiePolicy()); policies.add(new AddDatePolicy()); policies.addAll(this.perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); if (credential != null) { policies.add(new ContainerRegistryCredentialsPolicy( credential, endpoint, new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(), serializerAdapter )); } HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return httpPipeline; } /** * Builds an instance of ContainerRegistryClient sync client. * * @return an instance of ContainerRegistryClient. */ public ContainerRepositoryClient buildClient() { return new ContainerRepositoryClient(buildAsyncClient()); } }
class ContainerRepositoryClientBuilder { private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-containers-containerregistry.properties"); private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion"); private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private String endpoint; private HttpClient httpClient; private TokenCredential credential; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions; private SerializerAdapter serializerAdapter; private RetryPolicy retryPolicy; private String repository; private ContainerRegistryServiceVersion version; /** * Sets Registry login URL. * * @throws IllegalArgumentException if endpoint is not a valid URL. * @param endpoint the endpoint value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets repository name. * @param repository non null repository name * * @throws NullPointerException if repository name is null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder repository(String repository) { this.repository = Objects.requireNonNull(repository, "'repository' cannot be null."); return this; } /** * Sets Registry login URL. * * @param credential the credential to use to access registry. * @throws NullPointerException if credential is null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder credential(TokenCredential credential) { this.credential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets The HTTP httpPipeline to send requests through. * * @param httpPipeline the httpPipeline value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the service version that will be targeted by the client. * * @param version the service version to target. * @return the ContainerRegistryBuilder. */ public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) { this.version = version; return this; } /** * Sets The HTTP client used to send the request. * * @param httpClient the httpClient value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Sets the client options such as application ID and custom headers to set on a request. * * @param clientOptions The {@link ClientOptions}. * @return The updated {@code TableClientBuilder}. */ public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets The configuration store that is used during construction of the service client. * * @param configuration the configuration value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets The logging configuration for HTTP requests and responses. * * @param httpLogOptions the httpLogOptions value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Adds a custom Http httpPipeline policy. * * @param customPolicy The custom Http httpPipeline policy to add. * @throws NullPointerException custom policy can't be null. * @return the ContainerRepositoryClientBuilder. */ public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(customPolicy); } else { perRetryPolicies.add(customPolicy); } return this; } /** * Builds an instance of ContainerRegistryImpl with the provided parameters. * * @return an instance of ContainerRegistryImpl. */ private HttpPipeline getHttpPipeline() { if (httpPipeline != null) { return httpPipeline; } Objects.requireNonNull(credential, "'credential' cannot be null."); return Utils.buildHttpPipeline( this.clientOptions, this.httpLogOptions, this.configuration, this.retryPolicy, this.credential, this.perCallPolicies, this.perRetryPolicies, this.httpClient, this.endpoint); } /** * Builds an instance of ContainerRegistryClient sync client. * * @return an instance of ContainerRegistryClient. */ public ContainerRepositoryClient buildClient() { return new ContainerRepositoryClient(buildAsyncClient()); } }
I did not see any issues, however when I came across Content.None I assumed null is not supported. --- In reply to: [609122416](https://github.com/Azure/azure-sdk-for-java/pull/20368#discussion_r609122416) [](ancestors = 609122416)
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } }
return monoError(logger, new NullPointerException("'context' cannot be null."));
return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final SerializerAdapter serializerAdapter; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String version) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .serializerAdapter(serializerAdapter).buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List repositories. * * @return list of repositories. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, apiVersion); } }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, String endpoint, String version) { this.httpPipeline = httpPipeline; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List all the repository names in this registry. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of repository names. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the repository (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the image (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, endpoint, apiVersion); } }
Right now yes. We want to eventually add a convenience layer where that is not the case. --- In reply to: [609151484](https://github.com/Azure/azure-sdk-for-java/pull/20368#discussion_r609151484) [](ancestors = 609151484)
public String getRegistry() { return this.endpoint; }
return this.endpoint;
public String getRegistry() { return this.endpoint; }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializerAdapter) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } /** * Delete repository. * * @param context Context associated with the operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().map(Response::getValue); } /** * Delete registry artifact. * * @param digest Digest name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Delete tag. * * @param tag tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().map(Response::getValue); } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<String> getTagMono = Mono.defer( () -> tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest())); return getTagMono .flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).map(Response::getValue); } /** * List registry artifacts based of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List manifests of a repository. * * @param options the options associated with the list registy operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).map(Response::getValue); } /** * List tags of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value) .flatMap((Response<Void> res) -> Mono.empty()); } }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().flatMap(FluxUtil::toMono); } /** * Delete registry artifact. * * @param digest the digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest).flatMap(FluxUtil::toMono); } /** * Delete tag. * * @param tag tag to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag tag to delete * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag).flatMap(FluxUtil::toMono); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given repository was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { Mono<String> getTagMono = tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest()); return getTagMono .flatMap(digest -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, digest)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).flatMap(FluxUtil::toMono); } /** * List registry artifacts of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List registry artifacts of a repository. * * @param options the options associated with the list registry operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).flatMap(FluxUtil::toMono); } /** * List tags of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value).flatMap(FluxUtil::toMono); } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value).flatMap(FluxUtil::toMono); } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value).flatMap(FluxUtil::toMono); } }
Looked at the fluxutil methods and I believe you mean FluxUtil::toMono --> did not know it existed, changed - Thanks! --- In reply to: [609152718](https://github.com/Azure/azure-sdk-for-java/pull/20368#discussion_r609152718) [](ancestors = 609152718)
public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest) .flatMap((Response<Void> res) -> Mono.empty()); }
.flatMap((Response<Void> res) -> Mono.empty());
public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest).flatMap(FluxUtil::toMono); }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializerAdapter) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } /** * Delete repository. * * @param context Context associated with the operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().map(Response::getValue); } /** * Delete registry artifact. * * @param digest Digest name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Delete tag. * * @param tag tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().map(Response::getValue); } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<String> getTagMono = Mono.defer( () -> tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest())); return getTagMono .flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).map(Response::getValue); } /** * List registry artifacts based of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List manifests of a repository. * * @param options the options associated with the list registy operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).map(Response::getValue); } /** * List tags of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value) .flatMap((Response<Void> res) -> Mono.empty()); } }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().flatMap(FluxUtil::toMono); } /** * Delete registry artifact. * * @param digest the digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Delete tag. * * @param tag tag to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag tag to delete * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag).flatMap(FluxUtil::toMono); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given repository was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { Mono<String> getTagMono = tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest()); return getTagMono .flatMap(digest -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, digest)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).flatMap(FluxUtil::toMono); } /** * List registry artifacts of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List registry artifacts of a repository. * * @param options the options associated with the list registry operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).flatMap(FluxUtil::toMono); } /** * List tags of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value).flatMap(FluxUtil::toMono); } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value).flatMap(FluxUtil::toMono); } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value).flatMap(FluxUtil::toMono); } }
Why doesn't the next page API use the pageSize? #Resolved
public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); }
(token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final SerializerAdapter serializerAdapter; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String version) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .serializerAdapter(serializerAdapter).buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List repositories. * * @return list of repositories. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, apiVersion); } }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, String endpoint, String version) { this.httpPipeline = httpPipeline; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List all the repository names in this registry. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of repository names. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the repository (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the image (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, endpoint, apiVersion); } }
Yeah, null is supported. If the input is null, just replace it with `Context.NONE` instead of returning an error. #Resolved
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } }
return monoError(logger, new NullPointerException("'context' cannot be null."));
return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final SerializerAdapter serializerAdapter; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String version) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .serializerAdapter(serializerAdapter).buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List repositories. * * @return list of repositories. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, apiVersion); } }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, String endpoint, String version) { this.httpPipeline = httpPipeline; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List all the repository names in this registry. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of repository names. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the repository (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the image (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, endpoint, apiVersion); } }
How does the user set the pageSize? #Resolved
public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); }
(pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)),
public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializerAdapter) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } /** * Delete repository. * * @param context Context associated with the operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().map(Response::getValue); } /** * Delete registry artifact. * * @param digest Digest name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Delete tag. * * @param tag tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().map(Response::getValue); } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<String> getTagMono = Mono.defer( () -> tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest())); return getTagMono .flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).map(Response::getValue); } /** * List registry artifacts based of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List manifests of a repository. * * @param options the options associated with the list registy operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).map(Response::getValue); } /** * List tags of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value) .flatMap((Response<Void> res) -> Mono.empty()); } }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().flatMap(FluxUtil::toMono); } /** * Delete registry artifact. * * @param digest the digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest).flatMap(FluxUtil::toMono); } /** * Delete tag. * * @param tag tag to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag tag to delete * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag).flatMap(FluxUtil::toMono); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given repository was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { Mono<String> getTagMono = tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest()); return getTagMono .flatMap(digest -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, digest)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).flatMap(FluxUtil::toMono); } /** * List registry artifacts of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List registry artifacts of a repository. * * @param options the options associated with the list registry operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).flatMap(FluxUtil::toMono); } /** * List tags of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value).flatMap(FluxUtil::toMono); } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value).flatMap(FluxUtil::toMono); } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value).flatMap(FluxUtil::toMono); } }
It is already part of the continutation token --- In reply to: [609604500](https://github.com/Azure/azure-sdk-for-java/pull/20368#discussion_r609604500) [](ancestors = 609604500)
public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); }
(token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final SerializerAdapter serializerAdapter; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String version) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .serializerAdapter(serializerAdapter).buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List repositories. * * @return list of repositories. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, apiVersion); } }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, String endpoint, String version) { this.httpPipeline = httpPipeline; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List all the repository names in this registry. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of repository names. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the repository (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the image (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, endpoint, apiVersion); } }
Removed. --- In reply to: [609181320](https://github.com/Azure/azure-sdk-for-java/pull/20368#discussion_r609181320) [](ancestors = 609181320,609122416)
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } }
return monoError(logger, new NullPointerException("'context' cannot be null."));
return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final SerializerAdapter serializerAdapter; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String version) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .serializerAdapter(serializerAdapter).buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List repositories. * * @return list of repositories. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesSinglePageAsync(null, pageSize, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res)) .onErrorMap(Utils::mapException); return pagedResponseMono; } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by `name`. * * @param name Name of the image (including the namespace). * @return deleted repository. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, apiVersion); } }
class ContainerRegistryAsyncClient { private final ContainerRegistryImpl registryImplClient; private final ContainerRegistriesImpl registriesImplClient; private final HttpPipeline httpPipeline; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class); ContainerRegistryAsyncClient(HttpPipeline httpPipeline, String endpoint, String version) { this.httpPipeline = httpPipeline; this.endpoint = endpoint; this.registryImplClient = new ContainerRegistryImplBuilder() .url(endpoint) .pipeline(httpPipeline) .buildClient(); this.registriesImplClient = this.registryImplClient.getContainerRegistries(); this.apiVersion = version; } /** * List all the repository names in this registry. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of repository names. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<String> listRepositories() { return new PagedFlux<>( (pageSize) -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)), (token, pageSize) -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context))); } PagedFlux<String> listRepositories(Context context) { return new PagedFlux<>( (pageSize) -> listRepositoriesSinglePageAsync(pageSize, context), (token, pageSize) -> listRepositoriesNextSinglePageAsync(token, context)); } Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) { try { if (pageSize != null && pageSize < 0) { } Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) { try { Mono<PagedResponse<String>> pagedResponseMono = this.registriesImplClient.getRepositoriesNextSinglePageAsync(nextLink, context); return pagedResponseMono.map(res -> Utils.getPagedResponseWithContinuationToken(res)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the repository (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) { return withContext(context -> deleteRepositoryWithResponse(name, context)); } Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) { try { if (name == null) { return monoError(logger, new NullPointerException("'name' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(name, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Delete the repository identified by 'name'. * * @param name Name of the image (including the namespace). * @return deleted repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @throws NullPointerException thrown if the name is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> deleteRepository(String name) { return withContext(context -> this.deleteRepository(name, context)); } Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) { return this.deleteRepositoryWithResponse(name, context).map(Response::getValue); } /** * Get an instance of repository client from the registry client. * * @param repository Name of the repository (including the namespace). * @return repository client. */ public ContainerRepositoryAsyncClient getRepositoryClient(String repository) { return new ContainerRepositoryAsyncClient(repository, httpPipeline, endpoint, apiVersion); } }
by calling the listTags.byPage(pageSize) --> it is one of the overloads of byPage(int pageSize). --- In reply to: [609640147](https://github.com/Azure/azure-sdk-for-java/pull/20368#discussion_r609640147) [](ancestors = 609640147)
public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); }
(pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)),
public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializerAdapter) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } /** * Delete repository. * * @param context Context associated with the operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().map(Response::getValue); } /** * Delete registry artifact. * * @param digest Digest name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Delete tag. * * @param tag tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().map(Response::getValue); } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } Mono<String> getTagMono = Mono.defer( () -> tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest())); return getTagMono .flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get registry artifact properties. * * @param tagOrDigest tag or digest associated with the blob. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).map(Response::getValue); } /** * List registry artifacts based of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List manifests of a repository. * * @param options the options associated with the list registy operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag Tag name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).map(Response::getValue); } /** * List tags of a repository. * * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the attribute identified by `name` where `reference` is the name of the repository. * * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value) .flatMap((Response<Void> res) -> Mono.empty()); } }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().flatMap(FluxUtil::toMono); } /** * Delete registry artifact. * * @param digest the digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest).flatMap(FluxUtil::toMono); } /** * Delete tag. * * @param tag tag to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag tag to delete * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag).flatMap(FluxUtil::toMono); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given repository was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { Mono<String> getTagMono = tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest()); return getTagMono .flatMap(digest -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, digest)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).flatMap(FluxUtil::toMono); } /** * List registry artifacts of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List registry artifacts of a repository. * * @param options the options associated with the list registry operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).flatMap(FluxUtil::toMono); } /** * List tags of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value).flatMap(FluxUtil::toMono); } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value).flatMap(FluxUtil::toMono); } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value).flatMap(FluxUtil::toMono); } }
I think the above mono resolves this to a `digest` right? So, should this be a `digest` instead of a tag? ```suggestion .flatMap(digest-> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, digest)) ``` #Resolved
Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { Mono<String> getTagMono = tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest()); return getTagMono .flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } }
.flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag))
return monoError(logger, ex); } } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeleteRepositoryResult> delete() { return this.deleteWithResponse().flatMap(FluxUtil::toMono); }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } /** * Delete repository. * * @param context Context associated with the operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { /** * Delete registry artifact. * * @param digest Digest name. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest).flatMap(FluxUtil::toMono); } /** * Delete tag. * * @param tag tag name. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag Tag name. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag).flatMap(FluxUtil::toMono); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the blob. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { Mono<String> getTagMono = tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest()); return getTagMono .flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the blob. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).flatMap(FluxUtil::toMono); } /** * List registry artifacts based of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List manifests of a repository. * * @param options the options associated with the list registy operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag Tag name. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag Tag name. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return tag attributes by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).flatMap(FluxUtil::toMono); } /** * List tags of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Repository attribute value. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Repository attribute value. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value).flatMap(FluxUtil::toMono); } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag attributes. * * @param tag Tag name. * @param value Repository attribute value. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value).flatMap(FluxUtil::toMono); } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update attributes of a manifest. * * @param digest Digest of a BLOB. * @param value Repository attribute value. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value).flatMap(FluxUtil::toMono); } }
class ContainerRepositoryAsyncClient { private final ContainerRegistryRepositoriesImpl serviceClient; private final ContainerRegistriesImpl registriesImplClient; private final String repositoryName; private final String endpoint; private final String apiVersion; private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class); ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String apiVersion) { if (repositoryName == null) { throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null")); } ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder() .pipeline(httpPipeline) .url(endpoint).buildClient(); this.endpoint = endpoint; this.repositoryName = repositoryName; this.registriesImplClient = registryImpl.getContainerRegistries(); this.serviceClient = registryImpl.getContainerRegistryRepositories(); this.apiVersion = apiVersion; } /** * Get endpoint associated with the class. * @return String the endpoint associated with this client. */ public String getEndpoint() { return this.endpoint; } /** * Get the registry associated with the client. * @return Return the registry name. */ public String getRegistry() { return this.endpoint; } /** * Get repository associated with the class. * @return Return the repository name. * */ public String getRepository() { return this.repositoryName; } /** * Delete the repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given name was not found. * @return deleted repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() { return withContext(context -> deleteWithResponse(context)); } Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) { try { return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { /** * Delete registry artifact. * * @param digest the digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) { return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context)); } Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete registry artifact. * * @param digest digest to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if digest is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRegistryArtifact(String digest) { return this.deleteRegistryArtifactWithResponse(digest).flatMap(FluxUtil::toMono); } /** * Delete tag. * * @param tag tag to delete. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTagWithResponse(String tag) { return withContext(context -> this.deleteTagWithResponse(tag, context)); } Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'digest' cannot be null")); } return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Delete tag. * * @param tag tag to delete * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @throws NullPointerException thrown if tag is null. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTag(String tag) { return this.deleteTagWithResponse(tag).flatMap(FluxUtil::toMono); } /** * Get repository properties. * * @return repository properties. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() { return withContext(context -> this.getPropertiesWithResponse(context)); } Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) { try { if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context) .map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get repository properties. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given repository was not found. * @return repository properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RepositoryProperties> getProperties() { return this.getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) { return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context)); } Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) { try { Mono<String> getTagMono = tagOrDigest.contains(":") ? Mono.just(tagOrDigest) : this.getTagProperties(tagOrDigest).map(a -> a.getDigest()); return getTagMono .flatMap(digest -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, digest)) .map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * <p>Get registry artifact properties.</p> * * <p>This method can take in both a digest as well as a tag.<br> * In case a tag is provided it calls the service to get the digest associated with it.</p> * @param tagOrDigest tag or digest associated with the artifact. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return registry artifact properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) { return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).flatMap(FluxUtil::toMono); } /** * List registry artifacts of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() { return listRegistryArtifacts(null); } /** * List registry artifacts of a repository. * * @param options the options associated with the list registry operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return manifest attributes. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context))); } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getRegistryArtifactOrderBy() != null) { orderBy = options.getRegistryArtifactOrderBy().toString(); } return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Get tag properties * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) { return withContext(context -> getTagPropertiesWithResponse(tag, context)); } Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context) .map(res -> Utils.mapResponse(res, Utils::mapTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get tag attributes. * * @param tag name of the tag. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return tag properties by tag. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TagProperties> getTagProperties(String tag) { return this.getTagPropertiesWithResponse(tag).flatMap(FluxUtil::toMono); } /** * List tags of a repository. * * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags() { return listTags(null); } /** * List tags of a repository. * * @param options tagOptions to be used for the given operation. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return list of tag details. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TagProperties> listTags(ListTagsOptions options) { return new PagedFlux<>( (pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)), (token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context))); } Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) { try { if (pageSize != null && pageSize < 0) { return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative.")); } String orderBy = null; if (options != null && options.getTagOrderBy() != null) { orderBy = options.getTagOrderBy().toString(); } return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) { Objects.requireNonNull(baseValues); return baseValues.stream().map(value -> new TagProperties( value.getName(), repositoryName, value.getDigest(), value.getWriteableProperties(), value.getCreatedOn(), value.getLastUpdatedOn() )).collect(Collectors.toList()); } Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) { try { return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context) .map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties)); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) { return withContext(context -> this.setPropertiesWithResponse(value, context)); } Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) { try { if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update the content properties of the repository. * * @param value Content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setProperties(ContentProperties value) { return this.setPropertiesWithResponse(value).flatMap(FluxUtil::toMono); } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value) { return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context)); } Mono<Response<Void>> setTagPropertiesWithResponse( String tag, ContentProperties value, Context context) { try { if (tag == null) { return monoError(logger, new NullPointerException("'tag' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update tag properties. * * @param tag Name of the tag. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given tag was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setTagProperties(String tag, ContentProperties value) { return this.setTagPropertiesWithResponse(tag, value).flatMap(FluxUtil::toMono); } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setManifestPropertiesWithResponse( String digest, ContentProperties value) { return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context)); } Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) { try { if (digest == null) { return monoError(logger, new NullPointerException("'digest' cannot be null.")); } if (value == null) { return monoError(logger, new NullPointerException("'value' cannot be null.")); } return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context) .onErrorMap(Utils::mapException); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Update properties of a manifest. * * @param digest digest. * @param value content properties to be set. * @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace. * @throws ResourceNotFoundException thrown if the given digest was not found. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setManifestProperties(String digest, ContentProperties value) { return this.setManifestPropertiesWithResponse(digest, value).flatMap(FluxUtil::toMono); } }
how is this working for you? the service is returning: ``` "Unit": { "type": "number", "text": "hours", "boundingBox": [ 965, 1138, 1043, 1139, 1043, 1164, 965, 1162 ], "page": 1, "confidence": 0.895 }, ``` in .NET parsing to Float breaks the code.
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String invoiceUrl = "https: + "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeInvoicesPoller = client.beginRecognizeInvoicesFromUrl(invoiceUrl); List<RecognizedForm> recognizedInvoices = recognizeInvoicesPoller.getFinalResult(); for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedInvoice = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedInvoice.getFields(); System.out.printf("----------- Recognized invoice info for page %d -----------%n", i); FormField vendorNameField = recognizedFields.get("VendorName"); if (vendorNameField != null) { if (FieldValueType.STRING == vendorNameField.getValue().getValueType()) { String merchantName = vendorNameField.getValue().asString(); System.out.printf("Vendor Name: %s, confidence: %.2f%n", merchantName, vendorNameField.getConfidence()); } } FormField vendorAddressField = recognizedFields.get("VendorAddress"); if (vendorAddressField != null) { if (FieldValueType.STRING == vendorAddressField.getValue().getValueType()) { String merchantAddress = vendorAddressField.getValue().asString(); System.out.printf("Vendor address: %s, confidence: %.2f%n", merchantAddress, vendorAddressField.getConfidence()); } } FormField customerNameField = recognizedFields.get("CustomerName"); if (customerNameField != null) { if (FieldValueType.STRING == customerNameField.getValue().getValueType()) { String merchantAddress = customerNameField.getValue().asString(); System.out.printf("Customer Name: %s, confidence: %.2f%n", merchantAddress, customerNameField.getConfidence()); } } FormField customerAddressRecipientField = recognizedFields.get("CustomerAddressRecipient"); if (customerAddressRecipientField != null) { if (FieldValueType.STRING == customerAddressRecipientField.getValue().getValueType()) { String customerAddr = customerAddressRecipientField.getValue().asString(); System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n", customerAddr, customerAddressRecipientField.getConfidence()); } } FormField invoiceIdField = recognizedFields.get("InvoiceId"); if (invoiceIdField != null) { if (FieldValueType.STRING == invoiceIdField.getValue().getValueType()) { String invoiceId = invoiceIdField.getValue().asString(); System.out.printf("Invoice Id: %s, confidence: %.2f%n", invoiceId, invoiceIdField.getConfidence()); } } FormField invoiceDateField = recognizedFields.get("InvoiceDate"); if (customerNameField != null) { if (FieldValueType.DATE == invoiceDateField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateField.getConfidence()); } } FormField invoiceTotalField = recognizedFields.get("InvoiceTotal"); if (customerAddressRecipientField != null) { if (FieldValueType.FLOAT == invoiceTotalField.getValue().getValueType()) { Float invoiceTotal = invoiceTotalField.getValue().asFloat(); System.out.printf("Invoice Total: %.2f, confidence: %.2f%n", invoiceTotal, invoiceTotalField.getConfidence()); } } FormField invoiceItemsField = recognizedFields.get("Items"); if (invoiceItemsField != null) { System.out.printf("Invoice Items: %n"); if (FieldValueType.LIST == invoiceItemsField.getValue().getValueType()) { List<FormField> invoiceItems = invoiceItemsField.getValue().asList(); invoiceItems.stream() .filter(invoiceItem -> FieldValueType.MAP == invoiceItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Description".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String name = formField.getValue().asString(); System.out.printf("Description: %s, confidence: %.2fs%n", name, formField.getConfidence()); } } if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } if ("Unit".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unit = formField.getValue().asFloat(); System.out.printf("Unit: %f, confidence: %.2f%n", unit, formField.getConfidence()); } } if ("UnitPrice".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unitPrice = formField.getValue().asFloat(); System.out.printf("Unit Price: %f, confidence: %.2f%n", unitPrice, formField.getConfidence()); } } if ("ProductCode".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float productCode = formField.getValue().asFloat(); System.out.printf("Product Code: %f, confidence: %.2f%n", productCode, formField.getConfidence()); } } })); } } } }
Float unit = formField.getValue().asFloat();
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String invoiceUrl = "https: + "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeInvoicesPoller = client.beginRecognizeInvoicesFromUrl(invoiceUrl); List<RecognizedForm> recognizedInvoices = recognizeInvoicesPoller.getFinalResult(); for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedInvoice = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedInvoice.getFields(); System.out.printf("----------- Recognized invoice info for page %d -----------%n", i); FormField vendorNameField = recognizedFields.get("VendorName"); if (vendorNameField != null) { if (FieldValueType.STRING == vendorNameField.getValue().getValueType()) { String merchantName = vendorNameField.getValue().asString(); System.out.printf("Vendor Name: %s, confidence: %.2f%n", merchantName, vendorNameField.getConfidence()); } } FormField vendorAddressField = recognizedFields.get("VendorAddress"); if (vendorAddressField != null) { if (FieldValueType.STRING == vendorAddressField.getValue().getValueType()) { String merchantAddress = vendorAddressField.getValue().asString(); System.out.printf("Vendor address: %s, confidence: %.2f%n", merchantAddress, vendorAddressField.getConfidence()); } } FormField customerNameField = recognizedFields.get("CustomerName"); if (customerNameField != null) { if (FieldValueType.STRING == customerNameField.getValue().getValueType()) { String merchantAddress = customerNameField.getValue().asString(); System.out.printf("Customer Name: %s, confidence: %.2f%n", merchantAddress, customerNameField.getConfidence()); } } FormField customerAddressRecipientField = recognizedFields.get("CustomerAddressRecipient"); if (customerAddressRecipientField != null) { if (FieldValueType.STRING == customerAddressRecipientField.getValue().getValueType()) { String customerAddr = customerAddressRecipientField.getValue().asString(); System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n", customerAddr, customerAddressRecipientField.getConfidence()); } } FormField invoiceIdField = recognizedFields.get("InvoiceId"); if (invoiceIdField != null) { if (FieldValueType.STRING == invoiceIdField.getValue().getValueType()) { String invoiceId = invoiceIdField.getValue().asString(); System.out.printf("Invoice Id: %s, confidence: %.2f%n", invoiceId, invoiceIdField.getConfidence()); } } FormField invoiceDateField = recognizedFields.get("InvoiceDate"); if (customerNameField != null) { if (FieldValueType.DATE == invoiceDateField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateField.getConfidence()); } } FormField invoiceTotalField = recognizedFields.get("InvoiceTotal"); if (customerAddressRecipientField != null) { if (FieldValueType.FLOAT == invoiceTotalField.getValue().getValueType()) { Float invoiceTotal = invoiceTotalField.getValue().asFloat(); System.out.printf("Invoice Total: %.2f, confidence: %.2f%n", invoiceTotal, invoiceTotalField.getConfidence()); } } FormField invoiceItemsField = recognizedFields.get("Items"); if (invoiceItemsField != null) { System.out.printf("Invoice Items: %n"); if (FieldValueType.LIST == invoiceItemsField.getValue().getValueType()) { List<FormField> invoiceItems = invoiceItemsField.getValue().asList(); invoiceItems.stream() .filter(invoiceItem -> FieldValueType.MAP == invoiceItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Description".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String name = formField.getValue().asString(); System.out.printf("Description: %s, confidence: %.2fs%n", name, formField.getConfidence()); } } if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } if ("UnitPrice".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unitPrice = formField.getValue().asFloat(); System.out.printf("Unit Price: %f, confidence: %.2f%n", unitPrice, formField.getConfidence()); } } if ("ProductCode".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float productCode = formField.getValue().asFloat(); System.out.printf("Product Code: %f, confidence: %.2f%n", productCode, formField.getConfidence()); } } })); } } } }
class RecognizeInvoicesFromUrl { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
class RecognizeInvoicesFromUrl { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
So since the type is number the check on L140 would never be true and the value will not be printed. I dont think I have this code for line items checking in the tests yet.
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String invoiceUrl = "https: + "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeInvoicesPoller = client.beginRecognizeInvoicesFromUrl(invoiceUrl); List<RecognizedForm> recognizedInvoices = recognizeInvoicesPoller.getFinalResult(); for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedInvoice = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedInvoice.getFields(); System.out.printf("----------- Recognized invoice info for page %d -----------%n", i); FormField vendorNameField = recognizedFields.get("VendorName"); if (vendorNameField != null) { if (FieldValueType.STRING == vendorNameField.getValue().getValueType()) { String merchantName = vendorNameField.getValue().asString(); System.out.printf("Vendor Name: %s, confidence: %.2f%n", merchantName, vendorNameField.getConfidence()); } } FormField vendorAddressField = recognizedFields.get("VendorAddress"); if (vendorAddressField != null) { if (FieldValueType.STRING == vendorAddressField.getValue().getValueType()) { String merchantAddress = vendorAddressField.getValue().asString(); System.out.printf("Vendor address: %s, confidence: %.2f%n", merchantAddress, vendorAddressField.getConfidence()); } } FormField customerNameField = recognizedFields.get("CustomerName"); if (customerNameField != null) { if (FieldValueType.STRING == customerNameField.getValue().getValueType()) { String merchantAddress = customerNameField.getValue().asString(); System.out.printf("Customer Name: %s, confidence: %.2f%n", merchantAddress, customerNameField.getConfidence()); } } FormField customerAddressRecipientField = recognizedFields.get("CustomerAddressRecipient"); if (customerAddressRecipientField != null) { if (FieldValueType.STRING == customerAddressRecipientField.getValue().getValueType()) { String customerAddr = customerAddressRecipientField.getValue().asString(); System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n", customerAddr, customerAddressRecipientField.getConfidence()); } } FormField invoiceIdField = recognizedFields.get("InvoiceId"); if (invoiceIdField != null) { if (FieldValueType.STRING == invoiceIdField.getValue().getValueType()) { String invoiceId = invoiceIdField.getValue().asString(); System.out.printf("Invoice Id: %s, confidence: %.2f%n", invoiceId, invoiceIdField.getConfidence()); } } FormField invoiceDateField = recognizedFields.get("InvoiceDate"); if (customerNameField != null) { if (FieldValueType.DATE == invoiceDateField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateField.getConfidence()); } } FormField invoiceTotalField = recognizedFields.get("InvoiceTotal"); if (customerAddressRecipientField != null) { if (FieldValueType.FLOAT == invoiceTotalField.getValue().getValueType()) { Float invoiceTotal = invoiceTotalField.getValue().asFloat(); System.out.printf("Invoice Total: %.2f, confidence: %.2f%n", invoiceTotal, invoiceTotalField.getConfidence()); } } FormField invoiceItemsField = recognizedFields.get("Items"); if (invoiceItemsField != null) { System.out.printf("Invoice Items: %n"); if (FieldValueType.LIST == invoiceItemsField.getValue().getValueType()) { List<FormField> invoiceItems = invoiceItemsField.getValue().asList(); invoiceItems.stream() .filter(invoiceItem -> FieldValueType.MAP == invoiceItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Description".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String name = formField.getValue().asString(); System.out.printf("Description: %s, confidence: %.2fs%n", name, formField.getConfidence()); } } if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } if ("Unit".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unit = formField.getValue().asFloat(); System.out.printf("Unit: %f, confidence: %.2f%n", unit, formField.getConfidence()); } } if ("UnitPrice".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unitPrice = formField.getValue().asFloat(); System.out.printf("Unit Price: %f, confidence: %.2f%n", unitPrice, formField.getConfidence()); } } if ("ProductCode".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float productCode = formField.getValue().asFloat(); System.out.printf("Product Code: %f, confidence: %.2f%n", productCode, formField.getConfidence()); } } })); } } } }
Float unit = formField.getValue().asFloat();
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String invoiceUrl = "https: + "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeInvoicesPoller = client.beginRecognizeInvoicesFromUrl(invoiceUrl); List<RecognizedForm> recognizedInvoices = recognizeInvoicesPoller.getFinalResult(); for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedInvoice = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedInvoice.getFields(); System.out.printf("----------- Recognized invoice info for page %d -----------%n", i); FormField vendorNameField = recognizedFields.get("VendorName"); if (vendorNameField != null) { if (FieldValueType.STRING == vendorNameField.getValue().getValueType()) { String merchantName = vendorNameField.getValue().asString(); System.out.printf("Vendor Name: %s, confidence: %.2f%n", merchantName, vendorNameField.getConfidence()); } } FormField vendorAddressField = recognizedFields.get("VendorAddress"); if (vendorAddressField != null) { if (FieldValueType.STRING == vendorAddressField.getValue().getValueType()) { String merchantAddress = vendorAddressField.getValue().asString(); System.out.printf("Vendor address: %s, confidence: %.2f%n", merchantAddress, vendorAddressField.getConfidence()); } } FormField customerNameField = recognizedFields.get("CustomerName"); if (customerNameField != null) { if (FieldValueType.STRING == customerNameField.getValue().getValueType()) { String merchantAddress = customerNameField.getValue().asString(); System.out.printf("Customer Name: %s, confidence: %.2f%n", merchantAddress, customerNameField.getConfidence()); } } FormField customerAddressRecipientField = recognizedFields.get("CustomerAddressRecipient"); if (customerAddressRecipientField != null) { if (FieldValueType.STRING == customerAddressRecipientField.getValue().getValueType()) { String customerAddr = customerAddressRecipientField.getValue().asString(); System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n", customerAddr, customerAddressRecipientField.getConfidence()); } } FormField invoiceIdField = recognizedFields.get("InvoiceId"); if (invoiceIdField != null) { if (FieldValueType.STRING == invoiceIdField.getValue().getValueType()) { String invoiceId = invoiceIdField.getValue().asString(); System.out.printf("Invoice Id: %s, confidence: %.2f%n", invoiceId, invoiceIdField.getConfidence()); } } FormField invoiceDateField = recognizedFields.get("InvoiceDate"); if (customerNameField != null) { if (FieldValueType.DATE == invoiceDateField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateField.getConfidence()); } } FormField invoiceTotalField = recognizedFields.get("InvoiceTotal"); if (customerAddressRecipientField != null) { if (FieldValueType.FLOAT == invoiceTotalField.getValue().getValueType()) { Float invoiceTotal = invoiceTotalField.getValue().asFloat(); System.out.printf("Invoice Total: %.2f, confidence: %.2f%n", invoiceTotal, invoiceTotalField.getConfidence()); } } FormField invoiceItemsField = recognizedFields.get("Items"); if (invoiceItemsField != null) { System.out.printf("Invoice Items: %n"); if (FieldValueType.LIST == invoiceItemsField.getValue().getValueType()) { List<FormField> invoiceItems = invoiceItemsField.getValue().asList(); invoiceItems.stream() .filter(invoiceItem -> FieldValueType.MAP == invoiceItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Description".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String name = formField.getValue().asString(); System.out.printf("Description: %s, confidence: %.2fs%n", name, formField.getConfidence()); } } if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } if ("UnitPrice".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unitPrice = formField.getValue().asFloat(); System.out.printf("Unit Price: %f, confidence: %.2f%n", unitPrice, formField.getConfidence()); } } if ("ProductCode".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float productCode = formField.getValue().asFloat(); System.out.printf("Product Code: %f, confidence: %.2f%n", productCode, formField.getConfidence()); } } })); } } } }
class RecognizeInvoicesFromUrl { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
class RecognizeInvoicesFromUrl { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
Also, just checked the sample_invoice.jpg currently is returning just these fields ```java "Amount" "Description" "Quantity" "UnitPrice" ```
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String invoiceUrl = "https: + "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeInvoicesPoller = client.beginRecognizeInvoicesFromUrl(invoiceUrl); List<RecognizedForm> recognizedInvoices = recognizeInvoicesPoller.getFinalResult(); for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedInvoice = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedInvoice.getFields(); System.out.printf("----------- Recognized invoice info for page %d -----------%n", i); FormField vendorNameField = recognizedFields.get("VendorName"); if (vendorNameField != null) { if (FieldValueType.STRING == vendorNameField.getValue().getValueType()) { String merchantName = vendorNameField.getValue().asString(); System.out.printf("Vendor Name: %s, confidence: %.2f%n", merchantName, vendorNameField.getConfidence()); } } FormField vendorAddressField = recognizedFields.get("VendorAddress"); if (vendorAddressField != null) { if (FieldValueType.STRING == vendorAddressField.getValue().getValueType()) { String merchantAddress = vendorAddressField.getValue().asString(); System.out.printf("Vendor address: %s, confidence: %.2f%n", merchantAddress, vendorAddressField.getConfidence()); } } FormField customerNameField = recognizedFields.get("CustomerName"); if (customerNameField != null) { if (FieldValueType.STRING == customerNameField.getValue().getValueType()) { String merchantAddress = customerNameField.getValue().asString(); System.out.printf("Customer Name: %s, confidence: %.2f%n", merchantAddress, customerNameField.getConfidence()); } } FormField customerAddressRecipientField = recognizedFields.get("CustomerAddressRecipient"); if (customerAddressRecipientField != null) { if (FieldValueType.STRING == customerAddressRecipientField.getValue().getValueType()) { String customerAddr = customerAddressRecipientField.getValue().asString(); System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n", customerAddr, customerAddressRecipientField.getConfidence()); } } FormField invoiceIdField = recognizedFields.get("InvoiceId"); if (invoiceIdField != null) { if (FieldValueType.STRING == invoiceIdField.getValue().getValueType()) { String invoiceId = invoiceIdField.getValue().asString(); System.out.printf("Invoice Id: %s, confidence: %.2f%n", invoiceId, invoiceIdField.getConfidence()); } } FormField invoiceDateField = recognizedFields.get("InvoiceDate"); if (customerNameField != null) { if (FieldValueType.DATE == invoiceDateField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateField.getConfidence()); } } FormField invoiceTotalField = recognizedFields.get("InvoiceTotal"); if (customerAddressRecipientField != null) { if (FieldValueType.FLOAT == invoiceTotalField.getValue().getValueType()) { Float invoiceTotal = invoiceTotalField.getValue().asFloat(); System.out.printf("Invoice Total: %.2f, confidence: %.2f%n", invoiceTotal, invoiceTotalField.getConfidence()); } } FormField invoiceItemsField = recognizedFields.get("Items"); if (invoiceItemsField != null) { System.out.printf("Invoice Items: %n"); if (FieldValueType.LIST == invoiceItemsField.getValue().getValueType()) { List<FormField> invoiceItems = invoiceItemsField.getValue().asList(); invoiceItems.stream() .filter(invoiceItem -> FieldValueType.MAP == invoiceItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Description".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String name = formField.getValue().asString(); System.out.printf("Description: %s, confidence: %.2fs%n", name, formField.getConfidence()); } } if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } if ("Unit".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unit = formField.getValue().asFloat(); System.out.printf("Unit: %f, confidence: %.2f%n", unit, formField.getConfidence()); } } if ("UnitPrice".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unitPrice = formField.getValue().asFloat(); System.out.printf("Unit Price: %f, confidence: %.2f%n", unitPrice, formField.getConfidence()); } } if ("ProductCode".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float productCode = formField.getValue().asFloat(); System.out.printf("Product Code: %f, confidence: %.2f%n", productCode, formField.getConfidence()); } } })); } } } }
Float unit = formField.getValue().asFloat();
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String invoiceUrl = "https: + "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeInvoicesPoller = client.beginRecognizeInvoicesFromUrl(invoiceUrl); List<RecognizedForm> recognizedInvoices = recognizeInvoicesPoller.getFinalResult(); for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedInvoice = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedInvoice.getFields(); System.out.printf("----------- Recognized invoice info for page %d -----------%n", i); FormField vendorNameField = recognizedFields.get("VendorName"); if (vendorNameField != null) { if (FieldValueType.STRING == vendorNameField.getValue().getValueType()) { String merchantName = vendorNameField.getValue().asString(); System.out.printf("Vendor Name: %s, confidence: %.2f%n", merchantName, vendorNameField.getConfidence()); } } FormField vendorAddressField = recognizedFields.get("VendorAddress"); if (vendorAddressField != null) { if (FieldValueType.STRING == vendorAddressField.getValue().getValueType()) { String merchantAddress = vendorAddressField.getValue().asString(); System.out.printf("Vendor address: %s, confidence: %.2f%n", merchantAddress, vendorAddressField.getConfidence()); } } FormField customerNameField = recognizedFields.get("CustomerName"); if (customerNameField != null) { if (FieldValueType.STRING == customerNameField.getValue().getValueType()) { String merchantAddress = customerNameField.getValue().asString(); System.out.printf("Customer Name: %s, confidence: %.2f%n", merchantAddress, customerNameField.getConfidence()); } } FormField customerAddressRecipientField = recognizedFields.get("CustomerAddressRecipient"); if (customerAddressRecipientField != null) { if (FieldValueType.STRING == customerAddressRecipientField.getValue().getValueType()) { String customerAddr = customerAddressRecipientField.getValue().asString(); System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n", customerAddr, customerAddressRecipientField.getConfidence()); } } FormField invoiceIdField = recognizedFields.get("InvoiceId"); if (invoiceIdField != null) { if (FieldValueType.STRING == invoiceIdField.getValue().getValueType()) { String invoiceId = invoiceIdField.getValue().asString(); System.out.printf("Invoice Id: %s, confidence: %.2f%n", invoiceId, invoiceIdField.getConfidence()); } } FormField invoiceDateField = recognizedFields.get("InvoiceDate"); if (customerNameField != null) { if (FieldValueType.DATE == invoiceDateField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateField.getConfidence()); } } FormField invoiceTotalField = recognizedFields.get("InvoiceTotal"); if (customerAddressRecipientField != null) { if (FieldValueType.FLOAT == invoiceTotalField.getValue().getValueType()) { Float invoiceTotal = invoiceTotalField.getValue().asFloat(); System.out.printf("Invoice Total: %.2f, confidence: %.2f%n", invoiceTotal, invoiceTotalField.getConfidence()); } } FormField invoiceItemsField = recognizedFields.get("Items"); if (invoiceItemsField != null) { System.out.printf("Invoice Items: %n"); if (FieldValueType.LIST == invoiceItemsField.getValue().getValueType()) { List<FormField> invoiceItems = invoiceItemsField.getValue().asList(); invoiceItems.stream() .filter(invoiceItem -> FieldValueType.MAP == invoiceItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Description".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String name = formField.getValue().asString(); System.out.printf("Description: %s, confidence: %.2fs%n", name, formField.getConfidence()); } } if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } if ("UnitPrice".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unitPrice = formField.getValue().asFloat(); System.out.printf("Unit Price: %f, confidence: %.2f%n", unitPrice, formField.getConfidence()); } } if ("ProductCode".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float productCode = formField.getValue().asFloat(); System.out.printf("Product Code: %f, confidence: %.2f%n", productCode, formField.getConfidence()); } } })); } } } }
class RecognizeInvoicesFromUrl { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
class RecognizeInvoicesFromUrl { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
If the service starts finding that field at some point will the sample break? Since you're only showing some of the line item fields, maybe just remove that one? Also, I saw that .NET added a small comment in their PR saying that only some of the fields were shown and then provided the aka.ms link with all the fields available. Would it make sense for java to do that too?
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String invoiceUrl = "https: + "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeInvoicesPoller = client.beginRecognizeInvoicesFromUrl(invoiceUrl); List<RecognizedForm> recognizedInvoices = recognizeInvoicesPoller.getFinalResult(); for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedInvoice = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedInvoice.getFields(); System.out.printf("----------- Recognized invoice info for page %d -----------%n", i); FormField vendorNameField = recognizedFields.get("VendorName"); if (vendorNameField != null) { if (FieldValueType.STRING == vendorNameField.getValue().getValueType()) { String merchantName = vendorNameField.getValue().asString(); System.out.printf("Vendor Name: %s, confidence: %.2f%n", merchantName, vendorNameField.getConfidence()); } } FormField vendorAddressField = recognizedFields.get("VendorAddress"); if (vendorAddressField != null) { if (FieldValueType.STRING == vendorAddressField.getValue().getValueType()) { String merchantAddress = vendorAddressField.getValue().asString(); System.out.printf("Vendor address: %s, confidence: %.2f%n", merchantAddress, vendorAddressField.getConfidence()); } } FormField customerNameField = recognizedFields.get("CustomerName"); if (customerNameField != null) { if (FieldValueType.STRING == customerNameField.getValue().getValueType()) { String merchantAddress = customerNameField.getValue().asString(); System.out.printf("Customer Name: %s, confidence: %.2f%n", merchantAddress, customerNameField.getConfidence()); } } FormField customerAddressRecipientField = recognizedFields.get("CustomerAddressRecipient"); if (customerAddressRecipientField != null) { if (FieldValueType.STRING == customerAddressRecipientField.getValue().getValueType()) { String customerAddr = customerAddressRecipientField.getValue().asString(); System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n", customerAddr, customerAddressRecipientField.getConfidence()); } } FormField invoiceIdField = recognizedFields.get("InvoiceId"); if (invoiceIdField != null) { if (FieldValueType.STRING == invoiceIdField.getValue().getValueType()) { String invoiceId = invoiceIdField.getValue().asString(); System.out.printf("Invoice Id: %s, confidence: %.2f%n", invoiceId, invoiceIdField.getConfidence()); } } FormField invoiceDateField = recognizedFields.get("InvoiceDate"); if (customerNameField != null) { if (FieldValueType.DATE == invoiceDateField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateField.getConfidence()); } } FormField invoiceTotalField = recognizedFields.get("InvoiceTotal"); if (customerAddressRecipientField != null) { if (FieldValueType.FLOAT == invoiceTotalField.getValue().getValueType()) { Float invoiceTotal = invoiceTotalField.getValue().asFloat(); System.out.printf("Invoice Total: %.2f, confidence: %.2f%n", invoiceTotal, invoiceTotalField.getConfidence()); } } FormField invoiceItemsField = recognizedFields.get("Items"); if (invoiceItemsField != null) { System.out.printf("Invoice Items: %n"); if (FieldValueType.LIST == invoiceItemsField.getValue().getValueType()) { List<FormField> invoiceItems = invoiceItemsField.getValue().asList(); invoiceItems.stream() .filter(invoiceItem -> FieldValueType.MAP == invoiceItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Description".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String name = formField.getValue().asString(); System.out.printf("Description: %s, confidence: %.2fs%n", name, formField.getConfidence()); } } if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } if ("Unit".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unit = formField.getValue().asFloat(); System.out.printf("Unit: %f, confidence: %.2f%n", unit, formField.getConfidence()); } } if ("UnitPrice".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unitPrice = formField.getValue().asFloat(); System.out.printf("Unit Price: %f, confidence: %.2f%n", unitPrice, formField.getConfidence()); } } if ("ProductCode".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float productCode = formField.getValue().asFloat(); System.out.printf("Product Code: %f, confidence: %.2f%n", productCode, formField.getConfidence()); } } })); } } } }
Float unit = formField.getValue().asFloat();
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String invoiceUrl = "https: + "azure-ai-formrecognizer/samples/sample_forms/forms/sample_invoice.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeInvoicesPoller = client.beginRecognizeInvoicesFromUrl(invoiceUrl); List<RecognizedForm> recognizedInvoices = recognizeInvoicesPoller.getFinalResult(); for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedInvoice = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedInvoice.getFields(); System.out.printf("----------- Recognized invoice info for page %d -----------%n", i); FormField vendorNameField = recognizedFields.get("VendorName"); if (vendorNameField != null) { if (FieldValueType.STRING == vendorNameField.getValue().getValueType()) { String merchantName = vendorNameField.getValue().asString(); System.out.printf("Vendor Name: %s, confidence: %.2f%n", merchantName, vendorNameField.getConfidence()); } } FormField vendorAddressField = recognizedFields.get("VendorAddress"); if (vendorAddressField != null) { if (FieldValueType.STRING == vendorAddressField.getValue().getValueType()) { String merchantAddress = vendorAddressField.getValue().asString(); System.out.printf("Vendor address: %s, confidence: %.2f%n", merchantAddress, vendorAddressField.getConfidence()); } } FormField customerNameField = recognizedFields.get("CustomerName"); if (customerNameField != null) { if (FieldValueType.STRING == customerNameField.getValue().getValueType()) { String merchantAddress = customerNameField.getValue().asString(); System.out.printf("Customer Name: %s, confidence: %.2f%n", merchantAddress, customerNameField.getConfidence()); } } FormField customerAddressRecipientField = recognizedFields.get("CustomerAddressRecipient"); if (customerAddressRecipientField != null) { if (FieldValueType.STRING == customerAddressRecipientField.getValue().getValueType()) { String customerAddr = customerAddressRecipientField.getValue().asString(); System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n", customerAddr, customerAddressRecipientField.getConfidence()); } } FormField invoiceIdField = recognizedFields.get("InvoiceId"); if (invoiceIdField != null) { if (FieldValueType.STRING == invoiceIdField.getValue().getValueType()) { String invoiceId = invoiceIdField.getValue().asString(); System.out.printf("Invoice Id: %s, confidence: %.2f%n", invoiceId, invoiceIdField.getConfidence()); } } FormField invoiceDateField = recognizedFields.get("InvoiceDate"); if (customerNameField != null) { if (FieldValueType.DATE == invoiceDateField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateField.getConfidence()); } } FormField invoiceTotalField = recognizedFields.get("InvoiceTotal"); if (customerAddressRecipientField != null) { if (FieldValueType.FLOAT == invoiceTotalField.getValue().getValueType()) { Float invoiceTotal = invoiceTotalField.getValue().asFloat(); System.out.printf("Invoice Total: %.2f, confidence: %.2f%n", invoiceTotal, invoiceTotalField.getConfidence()); } } FormField invoiceItemsField = recognizedFields.get("Items"); if (invoiceItemsField != null) { System.out.printf("Invoice Items: %n"); if (FieldValueType.LIST == invoiceItemsField.getValue().getValueType()) { List<FormField> invoiceItems = invoiceItemsField.getValue().asList(); invoiceItems.stream() .filter(invoiceItem -> FieldValueType.MAP == invoiceItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Description".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String name = formField.getValue().asString(); System.out.printf("Description: %s, confidence: %.2fs%n", name, formField.getConfidence()); } } if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } if ("UnitPrice".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float unitPrice = formField.getValue().asFloat(); System.out.printf("Unit Price: %f, confidence: %.2f%n", unitPrice, formField.getConfidence()); } } if ("ProductCode".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float productCode = formField.getValue().asFloat(); System.out.printf("Product Code: %f, confidence: %.2f%n", productCode, formField.getConfidence()); } } })); } } } }
class RecognizeInvoicesFromUrl { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
class RecognizeInvoicesFromUrl { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }