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 |
|---|---|---|---|---|---|
null check like you were doing in other places? | public RetryContext getRetryContext() {
return retryPolicy.getRetryContext();
} | return retryPolicy.getRetryContext(); | public RetryContext getRetryContext() {
if (this.retryPolicy != null) {
return this.retryPolicy.getRetryContext();
} else {
return null;
}
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} |
retryPolicy cannot be null , it get created during client init. If this is null nothing will work for the request | public RetryContext getRetryContext() {
return retryPolicy.getRetryContext();
} | return retryPolicy.getRetryContext(); | public RetryContext getRetryContext() {
if (this.retryPolicy != null) {
return this.retryPolicy.getRetryContext();
} else {
return null;
}
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} |
Same here - why is it ok to skip the check here but not upstream. Either we always consider IRetryPolicyFactory required/non-null in every retry policy in that case we can skip the null check everywhere (but should probably add it in the ctor of the RetryPolicy classes - the inconsistency is just making it harder to read - and avoids a clear contract (whether or not null is ok) | public RetryContext getRetryContext() {
return retryPolicy.getRetryContext();
} | return retryPolicy.getRetryContext(); | public RetryContext getRetryContext() {
if (this.retryPolicy != null) {
return this.retryPolicy.getRetryContext();
} else {
return null;
}
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} |
Please check this https://github.com/Azure/azure-sdk-for-java/blob/2ea8f94fb8523dbf4a6ee5961223df599a063620/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java#L435 , ResetSessionTokenRetryPolicyFactory is getting created with not null policy . So should be fine. | public RetryContext getRetryContext() {
return retryPolicy.getRetryContext();
} | return retryPolicy.getRetryContext(); | public RetryContext getRetryContext() {
if (this.retryPolicy != null) {
return this.retryPolicy.getRetryContext();
} else {
return null;
}
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} |
Gave another thought, no harm in having extra null check to be uniform across. Idea was here i knew for sure null wont come as it initialize during client creation. Have no strong opinion so adding a null check. | public RetryContext getRetryContext() {
return retryPolicy.getRetryContext();
} | return retryPolicy.getRetryContext(); | public RetryContext getRetryContext() {
if (this.retryPolicy != null) {
return this.retryPolicy.getRetryContext();
} else {
return null;
}
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} | class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory {
private final IRetryPolicyFactory retryPolicy;
private final ISessionContainer sessionContainer;
private final RxClientCollectionCache collectionCache;
public ResetSessionTokenRetryPolicyFactory(ISessionContainer sessionContainer, RxClientCollectionCache collectionCache, IRetryPolicyFactory retryPolicy) {
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
this.collectionCache = collectionCache;
}
@Override
public DocumentClientRetryPolicy getRequestPolicy() {
return new RenameCollectionAwareClientRetryPolicy(this.sessionContainer, this.collectionCache, retryPolicy.getRequestPolicy());
}
@Override
} |
Use the same param name in the error message. ```suggestion Objects.requireNonNull(policy, "'policy' cannot be null."); ``` #Resolved | public ContainerRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'customPolicy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
} | Objects.requireNonNull(policy, "'customPolicy' cannot be null."); | public ContainerRegistryClientBuilder 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;
} | class ContainerRegistryClientBuilder {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
}
private final ClientLogger logger = new ClientLogger(ContainerRegistryClientBuilder.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 RetryPolicy retryPolicy;
private ContainerRegistryServiceVersion version;
/**
* Sets the service endpoint for the Azure Container Registry instance.
*
* @param endpoint The URL of the Container Registry instance.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL.
*/
public ContainerRegistryClientBuilder 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 TokenCredential} used to authenticate REST Api calls.
*
* @param credential Azure Token credentials used to authenticate HTTP requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws NullPointerException if credential is null.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
* <p>
* If {@code pipeline} is set, all settings other than
* {@link
* to build {@link ContainerRegistryAsyncClient} or {@link ContainerRegistryClient}.<br>
* </p>
*
* This service takes dependency on an internal policy which converts Azure token credentials into Azure Container Registry specific service credentials.
* In case you use your own pipeline you will have to create your own credential policy.<br>
*
* {For more information please see <a href="https:
*
* @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the HTTP client to use for sending and receiving requests to and from the service.
*
* @param httpClient The HTTP client to use for requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
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 {@link ContainerRegistryClientBuilder} object
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
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 {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
* <p>
* If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param httpLogOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link
* build {@link ContainerRegistryClient} or {@link ContainerRegistryAsyncClient}.
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ContainerRegistryServiceVersion} 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 ContainerRegistryServiceVersion} of the service to be used when making requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
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.
*/
/**
* Creates a {@link ContainerRegistryAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ContainerRegistryAsyncClient} is created.
* <p>
* If {@link | class ContainerRegistryClientBuilder {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
}
private final ClientLogger logger = new ClientLogger(ContainerRegistryClientBuilder.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 RetryPolicy retryPolicy;
private ContainerRegistryServiceVersion version;
/**
* Sets the service endpoint for the Azure Container Registry instance.
*
* @param endpoint The URL of the Container Registry instance.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL.
*/
public ContainerRegistryClientBuilder 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 TokenCredential} used to authenticate REST API calls.
*
* @param credential Azure token credentials used to authenticate HTTP requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws NullPointerException if credential is null.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
* <p>
* If {@code pipeline} is set, all settings other than
* {@link
* to build {@link ContainerRegistryAsyncClient} or {@link ContainerRegistryClient}.
* </p>
*
* <p>The service does not directly support AAD credentials and as a result the clients internally depend on a policy that converts
* the AAD credentials to the Azure Container Registry specific service credentials. In case you use your own pipeline, you
* would need to provide implementation for this policy as well.
* For more information please see <a href="https:
*
* @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the HTTP client to use for sending requests to and receiving responses from the service.
*
* @param httpClient The HTTP client to use for requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* 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 {@link ContainerRegistryClientBuilder} object
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
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 to be used.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, HTTP request or response logging will not happen.</p>
*
* @param httpLogOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link
* build {@link ContainerRegistryClient} or {@link ContainerRegistryAsyncClient}.
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ContainerRegistryClientBuilder object.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ContainerRegistryServiceVersion} 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 and so
* newer version of the client library may result in moving to a newer service version.
*
* @param version {@link ContainerRegistryServiceVersion} of the service to be used when making requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
return this;
}
/**
* Adds a policy to the set of existing policies.
*
* @param policy The policy for service requests.
* @return The updated ContainerRegistryClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
/**
* Creates a {@link ContainerRegistryAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ContainerRegistryAsyncClient} is created.
* <p>
* If {@link |
Mind adding verbose level logging here when `this.httpPipeline` was previous set and is being set to null? AppConfiguration's and Search's client builders should have an example for this. #Resolved | public ContainerRegistryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
} | this.httpPipeline = httpPipeline; | public ContainerRegistryClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
} | class ContainerRegistryClientBuilder {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
}
private final ClientLogger logger = new ClientLogger(ContainerRegistryClientBuilder.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 RetryPolicy retryPolicy;
private ContainerRegistryServiceVersion version;
/**
* Sets the service endpoint for the Azure Container Registry instance.
*
* @param endpoint The URL of the Container Registry instance.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL.
*/
public ContainerRegistryClientBuilder 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 TokenCredential} used to authenticate REST Api calls.
*
* @param credential Azure Token credentials used to authenticate HTTP requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws NullPointerException if credential is null.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
* <p>
* If {@code pipeline} is set, all settings other than
* {@link
* to build {@link ContainerRegistryAsyncClient} or {@link ContainerRegistryClient}.<br>
* </p>
*
* This service takes dependency on an internal policy which converts Azure token credentials into Azure Container Registry specific service credentials.
* In case you use your own pipeline you will have to create your own credential policy.<br>
*
* {For more information please see <a href="https:
*
* @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
/**
* Sets the HTTP client to use for sending and receiving requests to and from the service.
*
* @param httpClient The HTTP client to use for requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
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 {@link ContainerRegistryClientBuilder} object
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
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 {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
* <p>
* If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param httpLogOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link
* build {@link ContainerRegistryClient} or {@link ContainerRegistryAsyncClient}.
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ContainerRegistryServiceVersion} 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 ContainerRegistryServiceVersion} of the service to be used when making requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
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 ContainerRegistryClientBuilder 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;
}
/**
* Creates a {@link ContainerRegistryAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ContainerRegistryAsyncClient} is created.
* <p>
* If {@link | class ContainerRegistryClientBuilder {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
}
private final ClientLogger logger = new ClientLogger(ContainerRegistryClientBuilder.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 RetryPolicy retryPolicy;
private ContainerRegistryServiceVersion version;
/**
* Sets the service endpoint for the Azure Container Registry instance.
*
* @param endpoint The URL of the Container Registry instance.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL.
*/
public ContainerRegistryClientBuilder 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 TokenCredential} used to authenticate REST API calls.
*
* @param credential Azure token credentials used to authenticate HTTP requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws NullPointerException if credential is null.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
* <p>
* If {@code pipeline} is set, all settings other than
* {@link
* to build {@link ContainerRegistryAsyncClient} or {@link ContainerRegistryClient}.
* </p>
*
* <p>The service does not directly support AAD credentials and as a result the clients internally depend on a policy that converts
* the AAD credentials to the Azure Container Registry specific service credentials. In case you use your own pipeline, you
* would need to provide implementation for this policy as well.
* For more information please see <a href="https:
*
* @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
/**
* Sets the HTTP client to use for sending requests to and receiving responses from the service.
*
* @param httpClient The HTTP client to use for requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* 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 {@link ContainerRegistryClientBuilder} object
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
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 to be used.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, HTTP request or response logging will not happen.</p>
*
* @param httpLogOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link
* build {@link ContainerRegistryClient} or {@link ContainerRegistryAsyncClient}.
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ContainerRegistryClientBuilder object.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ContainerRegistryServiceVersion} 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 and so
* newer version of the client library may result in moving to a newer service version.
*
* @param version {@link ContainerRegistryServiceVersion} of the service to be used when making requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
return this;
}
/**
* Adds a policy to the set of existing policies.
*
* @param policy The policy for service requests.
* @return The updated ContainerRegistryClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
public ContainerRegistryClientBuilder 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;
}
/**
* Creates a {@link ContainerRegistryAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ContainerRegistryAsyncClient} is created.
* <p>
* If {@link |
Same comment as `httpPipeline` about a verbose level log. #Resolved | public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
} | this.httpClient = httpClient; | public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
} | class ContainerRegistryClientBuilder {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
}
private final ClientLogger logger = new ClientLogger(ContainerRegistryClientBuilder.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 RetryPolicy retryPolicy;
private ContainerRegistryServiceVersion version;
/**
* Sets the service endpoint for the Azure Container Registry instance.
*
* @param endpoint The URL of the Container Registry instance.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL.
*/
public ContainerRegistryClientBuilder 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 TokenCredential} used to authenticate REST Api calls.
*
* @param credential Azure Token credentials used to authenticate HTTP requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws NullPointerException if credential is null.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
* <p>
* If {@code pipeline} is set, all settings other than
* {@link
* to build {@link ContainerRegistryAsyncClient} or {@link ContainerRegistryClient}.<br>
* </p>
*
* This service takes dependency on an internal policy which converts Azure token credentials into Azure Container Registry specific service credentials.
* In case you use your own pipeline you will have to create your own credential policy.<br>
*
* {For more information please see <a href="https:
*
* @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the HTTP client to use for sending and receiving requests to and from the service.
*
* @param httpClient The HTTP client to use for requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
/**
* 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 {@link ContainerRegistryClientBuilder} object
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
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 {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
* <p>
* If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param httpLogOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link
* build {@link ContainerRegistryClient} or {@link ContainerRegistryAsyncClient}.
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ContainerRegistryServiceVersion} 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 ContainerRegistryServiceVersion} of the service to be used when making requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
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 ContainerRegistryClientBuilder 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;
}
/**
* Creates a {@link ContainerRegistryAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ContainerRegistryAsyncClient} is created.
* <p>
* If {@link | class ContainerRegistryClientBuilder {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
}
private final ClientLogger logger = new ClientLogger(ContainerRegistryClientBuilder.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 RetryPolicy retryPolicy;
private ContainerRegistryServiceVersion version;
/**
* Sets the service endpoint for the Azure Container Registry instance.
*
* @param endpoint The URL of the Container Registry instance.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL.
*/
public ContainerRegistryClientBuilder 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 TokenCredential} used to authenticate REST API calls.
*
* @param credential Azure token credentials used to authenticate HTTP requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws NullPointerException if credential is null.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
* <p>
* If {@code pipeline} is set, all settings other than
* {@link
* to build {@link ContainerRegistryAsyncClient} or {@link ContainerRegistryClient}.
* </p>
*
* <p>The service does not directly support AAD credentials and as a result the clients internally depend on a policy that converts
* the AAD credentials to the Azure Container Registry specific service credentials. In case you use your own pipeline, you
* would need to provide implementation for this policy as well.
* For more information please see <a href="https:
*
* @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the HTTP client to use for sending requests to and receiving responses from the service.
*
* @param httpClient The HTTP client to use for requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
/**
* 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 {@link ContainerRegistryClientBuilder} object
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
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 to be used.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, HTTP request or response logging will not happen.</p>
*
* @param httpLogOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link
* build {@link ContainerRegistryClient} or {@link ContainerRegistryAsyncClient}.
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ContainerRegistryClientBuilder object.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ContainerRegistryServiceVersion} 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 and so
* newer version of the client library may result in moving to a newer service version.
*
* @param version {@link ContainerRegistryServiceVersion} of the service to be used when making requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
return this;
}
/**
* Adds a policy to the set of existing policies.
*
* @param policy The policy for service requests.
* @return The updated ContainerRegistryClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
public ContainerRegistryClientBuilder 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;
}
/**
* Creates a {@link ContainerRegistryAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ContainerRegistryAsyncClient} is created.
* <p>
* If {@link |
[doOnNext](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#doOnNext-java.util.function.Consumer-) or [doOnSuccess](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#doOnSuccess-java.util.function.Consumer-) might be more idiomatic for this purpose (instead of identity-map). | Mono<Response<String>> changeLeaseWithResponse(BlobChangeLeaseOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
Mono<Response<String>> response;
if (this.isBlob) {
response = this.client.getBlobs().changeLeaseWithResponseAsync(containerName, blobName, this.leaseId,
options.getProposedId(), null, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(),
requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
} else {
response = this.client.getContainers().changeLeaseWithResponseAsync(containerName, this.leaseId,
options.getProposedId(), null, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
}
response = response.map(r -> {
this.leaseId = r.getValue();
return r;
});
return response;
} | }); | new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
Mono<Response<String>> response;
if (this.isBlob) {
response = this.client.getBlobs().acquireLeaseWithResponseAsync(containerName, blobName, null,
options.getDuration(), this.leaseId, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(),
requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
} | class BlobLeaseAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobLeaseAsyncClient.class);
private final String containerName;
private final String blobName;
private final boolean isBlob;
private final AzureBlobStorageImpl client;
private final String accountName;
private volatile String leaseId;
BlobLeaseAsyncClient(HttpPipeline pipeline, String url, String containerName, String blobName, String leaseId,
boolean isBlob, String accountName, String serviceVersion) {
this.isBlob = isBlob;
this.leaseId = leaseId;
this.client = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion)
.buildClient();
this.accountName = accountName;
this.containerName = containerName;
this.blobName = blobName;
}
/**
* Gets the {@link URL} of the lease client.
*
* <p>The lease will either be a container or blob URL depending on which the lease client is associated.</p>
*
* @return URL of the lease client.
*/
public String getResourceUrl() {
if (this.isBlob) {
return this.client.getUrl() + "/" + containerName + "/" + blobName;
} else {
return this.client.getUrl() + "/" + containerName;
}
}
/**
* Get the lease ID for this lease.
*
* @return the lease ID.
*/
public String getLeaseId() {
return leaseId;
}
/**
* Acquires a lease for write and delete operations. The lease duration must be between 15 to 60 seconds or -1 for
* an infinite duration.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLease
*
* @param duration The duration of the lease between 15 to 60 seconds or -1 for an infinite duration.
* @return A reactive response containing the lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<String> acquireLease(int duration) {
try {
return acquireLeaseWithResponse(duration, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Acquires a lease for write and delete operations. The lease duration must be between 15 to 60 seconds, or -1 for
* an infinite duration.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse
*
* @param duration The duration of the lease between 15 to 60 seconds or -1 for an infinite duration.
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response containing the lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> acquireLeaseWithResponse(int duration, RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> acquireLeaseWithResponse(new BlobAcquireLeaseOptions(duration)
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Acquires a lease for write and delete operations. The lease duration must be between 15 to 60 seconds, or -1 for
* an infinite duration.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse
*
* @param options {@link BlobAcquireLeaseOptions}
* @return A reactive response containing the lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> acquireLeaseWithResponse(BlobAcquireLeaseOptions options) {
try {
return withContext(context -> acquireLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<String>> acquireLeaseWithResponse(BlobAcquireLeaseOptions options,
Context context) {
StorageImplUtils.assertNotNull("options", options);
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? else {
response = this.client.getContainers().acquireLeaseWithResponseAsync(containerName, null,
options.getDuration(), this.leaseId, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), null, context)
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
}
response = response.map(r -> {
this.leaseId = r.getValue();
return r;
});
return response;
}
/**
* Renews the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLease}
*
* @return A reactive response containing the renewed lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<String> renewLease() {
try {
return renewLeaseWithResponse((RequestConditions) null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Renews the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse
*
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response containing the renewed lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> renewLeaseWithResponse(RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> renewLeaseWithResponse(new BlobRenewLeaseOptions()
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Renews the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse
*
* @param options {@link BlobRenewLeaseOptions}
* @return A reactive response containing the renewed lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> renewLeaseWithResponse(BlobRenewLeaseOptions options) {
try {
return withContext(context -> renewLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<String>> renewLeaseWithResponse(BlobRenewLeaseOptions options, Context context) {
options = (options == null) ? new BlobRenewLeaseOptions() : options;
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
Mono<Response<String>> response;
if (this.isBlob) {
response = this.client.getBlobs().renewLeaseWithResponseAsync(containerName, blobName, this.leaseId, null,
requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(),
requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(),
requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
} else {
response = this.client.getContainers().renewLeaseWithResponseAsync(containerName, this.leaseId, null,
requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(),
null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
}
response = response.map(r -> {
this.leaseId = r.getValue();
return r;
});
return response;
}
/**
* Releases the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLease}
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> releaseLease() {
try {
return releaseLeaseWithResponse((RequestConditions) null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Releases the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse
*
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> releaseLeaseWithResponse(RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> releaseLeaseWithResponse(new BlobReleaseLeaseOptions()
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Releases the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse
*
* @param options {@link BlobReleaseLeaseOptions}
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> releaseLeaseWithResponse(BlobReleaseLeaseOptions options) {
try {
return withContext(context -> releaseLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> releaseLeaseWithResponse(BlobReleaseLeaseOptions options, Context context) {
options = (options == null) ? new BlobReleaseLeaseOptions() : options;
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
if (this.isBlob) {
return this.client.getBlobs().releaseLeaseWithResponseAsync(containerName, blobName, this.leaseId, null,
requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(),
requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(),
requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
} else {
return this.client.getContainers().releaseLeaseWithResponseAsync(containerName, this.leaseId, null,
requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(),
null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
}
/**
* Breaks the previously acquired lease, if it exists.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLease}
*
* @return A reactive response containing the remaining time in the broken lease in seconds.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Integer> breakLease() {
try {
return breakLeaseWithResponse((Integer) null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Breaks the previously acquired lease, if it exists.
*
* <p>If {@code null} is passed for {@code breakPeriodInSeconds} a fixed duration lease will break after the
* remaining lease period elapses and an infinite lease will break immediately.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse
*
* @param breakPeriodInSeconds An optional duration, between 0 and 60 seconds, that the lease should continue before
* it is broken. If the break period is longer than the time remaining on the lease the remaining time on the lease
* is used. A new lease will not be available before the break period has expired, but the lease may be held for
* longer than the break period.
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response containing the remaining time in the broken lease in seconds.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Integer>> breakLeaseWithResponse(Integer breakPeriodInSeconds,
RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> breakLeaseWithResponse(new BlobBreakLeaseOptions()
.setBreakPeriod(breakPeriodInSeconds == null ? null : Duration.ofSeconds(breakPeriodInSeconds))
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Breaks the previously acquired lease, if it exists.
*
* <p>If {@code null} is passed for {@code breakPeriodInSeconds} a fixed duration lease will break after the
* remaining lease period elapses and an infinite lease will break immediately.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse
*
* @param options {@link BlobBreakLeaseOptions}
* @return A reactive response containing the remaining time in the broken lease in seconds.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Integer>> breakLeaseWithResponse(BlobBreakLeaseOptions options) {
try {
return withContext(context -> breakLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Integer>> breakLeaseWithResponse(BlobBreakLeaseOptions options, Context context) {
options = (options == null) ? new BlobBreakLeaseOptions() : options;
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
Integer breakPeriod = options.getBreakPeriod() == null ? null
: Math.toIntExact(options.getBreakPeriod().getSeconds());
if (this.isBlob) {
return this.client.getBlobs().breakLeaseWithResponseAsync(containerName, blobName, null,
breakPeriod, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(),
requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseTime()));
} else {
return this.client.getContainers().breakLeaseWithResponseAsync(containerName, null,
breakPeriod, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), null, context)
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseTime()));
}
}
/**
* Changes the lease ID.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLease
*
* @param proposedId A new lease ID in a valid GUID format.
* @return A reactive response containing the new lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<String> changeLease(String proposedId) {
try {
return changeLeaseWithResponse(proposedId, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes the lease ID.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse
*
* @param proposedId A new lease ID in a valid GUID format.
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response containing the new lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> changeLeaseWithResponse(String proposedId,
RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> changeLeaseWithResponse(new BlobChangeLeaseOptions(proposedId)
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes the lease ID.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse
*
* @param options {@link BlobChangeLeaseOptions}
* @return A reactive response containing the new lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> changeLeaseWithResponse(BlobChangeLeaseOptions options) {
try {
return withContext(context -> changeLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<String>> changeLeaseWithResponse(BlobChangeLeaseOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
Mono<Response<String>> response;
if (this.isBlob) {
response = this.client.getBlobs().changeLeaseWithResponseAsync(containerName, blobName, this.leaseId,
options.getProposedId(), null, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(),
requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
} else {
response = this.client.getContainers().changeLeaseWithResponseAsync(containerName, this.leaseId,
options.getProposedId(), null, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
}
response = response.map(r -> {
this.leaseId = r.getValue();
return r;
});
return response;
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
} | class BlobLeaseAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobLeaseAsyncClient.class);
private final String containerName;
private final String blobName;
private final boolean isBlob;
private final AzureBlobStorageImpl client;
private final String accountName;
private volatile String leaseId;
BlobLeaseAsyncClient(HttpPipeline pipeline, String url, String containerName, String blobName, String leaseId,
boolean isBlob, String accountName, String serviceVersion) {
this.isBlob = isBlob;
this.leaseId = leaseId;
this.client = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion)
.buildClient();
this.accountName = accountName;
this.containerName = containerName;
this.blobName = blobName;
}
/**
* Gets the {@link URL} of the lease client.
*
* <p>The lease will either be a container or blob URL depending on which the lease client is associated.</p>
*
* @return URL of the lease client.
*/
public String getResourceUrl() {
if (this.isBlob) {
return this.client.getUrl() + "/" + containerName + "/" + blobName;
} else {
return this.client.getUrl() + "/" + containerName;
}
}
/**
* Get the lease ID for this lease.
*
* @return the lease ID.
*/
public String getLeaseId() {
return leaseId;
}
/**
* Acquires a lease for write and delete operations. The lease duration must be between 15 to 60 seconds or -1 for
* an infinite duration.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLease
*
* @param duration The duration of the lease between 15 to 60 seconds or -1 for an infinite duration.
* @return A reactive response containing the lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<String> acquireLease(int duration) {
try {
return acquireLeaseWithResponse(duration, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Acquires a lease for write and delete operations. The lease duration must be between 15 to 60 seconds, or -1 for
* an infinite duration.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse
*
* @param duration The duration of the lease between 15 to 60 seconds or -1 for an infinite duration.
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response containing the lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> acquireLeaseWithResponse(int duration, RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> acquireLeaseWithResponse(new BlobAcquireLeaseOptions(duration)
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Acquires a lease for write and delete operations. The lease duration must be between 15 to 60 seconds, or -1 for
* an infinite duration.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse
*
* @param options {@link BlobAcquireLeaseOptions}
* @return A reactive response containing the lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> acquireLeaseWithResponse(BlobAcquireLeaseOptions options) {
try {
return withContext(context -> acquireLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<String>> acquireLeaseWithResponse(BlobAcquireLeaseOptions options,
Context context) {
StorageImplUtils.assertNotNull("options", options);
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? else {
response = this.client.getContainers().acquireLeaseWithResponseAsync(containerName, null,
options.getDuration(), this.leaseId, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), null, context)
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
}
response = response.doOnSuccess(r -> this.leaseId = r.getValue());
return response;
}
/**
* Renews the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLease}
*
* @return A reactive response containing the renewed lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<String> renewLease() {
try {
return renewLeaseWithResponse((RequestConditions) null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Renews the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse
*
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response containing the renewed lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> renewLeaseWithResponse(RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> renewLeaseWithResponse(new BlobRenewLeaseOptions()
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Renews the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse
*
* @param options {@link BlobRenewLeaseOptions}
* @return A reactive response containing the renewed lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> renewLeaseWithResponse(BlobRenewLeaseOptions options) {
try {
return withContext(context -> renewLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<String>> renewLeaseWithResponse(BlobRenewLeaseOptions options, Context context) {
options = (options == null) ? new BlobRenewLeaseOptions() : options;
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
Mono<Response<String>> response;
if (this.isBlob) {
response = this.client.getBlobs().renewLeaseWithResponseAsync(containerName, blobName, this.leaseId, null,
requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(),
requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(),
requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
} else {
response = this.client.getContainers().renewLeaseWithResponseAsync(containerName, this.leaseId, null,
requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(),
null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
}
response = response.doOnSuccess(r -> this.leaseId = r.getValue());
return response;
}
/**
* Releases the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLease}
*
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> releaseLease() {
try {
return releaseLeaseWithResponse((RequestConditions) null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Releases the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse
*
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> releaseLeaseWithResponse(RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> releaseLeaseWithResponse(new BlobReleaseLeaseOptions()
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Releases the previously acquired lease.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse
*
* @param options {@link BlobReleaseLeaseOptions}
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> releaseLeaseWithResponse(BlobReleaseLeaseOptions options) {
try {
return withContext(context -> releaseLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> releaseLeaseWithResponse(BlobReleaseLeaseOptions options, Context context) {
options = (options == null) ? new BlobReleaseLeaseOptions() : options;
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
if (this.isBlob) {
return this.client.getBlobs().releaseLeaseWithResponseAsync(containerName, blobName, this.leaseId, null,
requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(),
requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(),
requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
} else {
return this.client.getContainers().releaseLeaseWithResponseAsync(containerName, this.leaseId, null,
requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(),
null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
}
/**
* Breaks the previously acquired lease, if it exists.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLease}
*
* @return A reactive response containing the remaining time in the broken lease in seconds.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Integer> breakLease() {
try {
return breakLeaseWithResponse((Integer) null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Breaks the previously acquired lease, if it exists.
*
* <p>If {@code null} is passed for {@code breakPeriodInSeconds} a fixed duration lease will break after the
* remaining lease period elapses and an infinite lease will break immediately.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse
*
* @param breakPeriodInSeconds An optional duration, between 0 and 60 seconds, that the lease should continue before
* it is broken. If the break period is longer than the time remaining on the lease the remaining time on the lease
* is used. A new lease will not be available before the break period has expired, but the lease may be held for
* longer than the break period.
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response containing the remaining time in the broken lease in seconds.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Integer>> breakLeaseWithResponse(Integer breakPeriodInSeconds,
RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> breakLeaseWithResponse(new BlobBreakLeaseOptions()
.setBreakPeriod(breakPeriodInSeconds == null ? null : Duration.ofSeconds(breakPeriodInSeconds))
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Breaks the previously acquired lease, if it exists.
*
* <p>If {@code null} is passed for {@code breakPeriodInSeconds} a fixed duration lease will break after the
* remaining lease period elapses and an infinite lease will break immediately.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse
*
* @param options {@link BlobBreakLeaseOptions}
* @return A reactive response containing the remaining time in the broken lease in seconds.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Integer>> breakLeaseWithResponse(BlobBreakLeaseOptions options) {
try {
return withContext(context -> breakLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Integer>> breakLeaseWithResponse(BlobBreakLeaseOptions options, Context context) {
options = (options == null) ? new BlobBreakLeaseOptions() : options;
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
Integer breakPeriod = options.getBreakPeriod() == null ? null
: Math.toIntExact(options.getBreakPeriod().getSeconds());
if (this.isBlob) {
return this.client.getBlobs().breakLeaseWithResponseAsync(containerName, blobName, null,
breakPeriod, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(),
requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseTime()));
} else {
return this.client.getContainers().breakLeaseWithResponseAsync(containerName, null,
breakPeriod, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), null, context)
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseTime()));
}
}
/**
* Changes the lease ID.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLease
*
* @param proposedId A new lease ID in a valid GUID format.
* @return A reactive response containing the new lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<String> changeLease(String proposedId) {
try {
return changeLeaseWithResponse(proposedId, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes the lease ID.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse
*
* @param proposedId A new lease ID in a valid GUID format.
* @param modifiedRequestConditions Standard HTTP Access conditions related to the modification of data. ETag and
* LastModifiedTime are used to construct conditions related to when the resource was changed relative to the given
* request. The request will fail if the specified condition is not satisfied.
* @return A reactive response containing the new lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> changeLeaseWithResponse(String proposedId,
RequestConditions modifiedRequestConditions) {
try {
return withContext(context -> changeLeaseWithResponse(new BlobChangeLeaseOptions(proposedId)
.setRequestConditions(ModelHelper.populateBlobLeaseRequestConditions(modifiedRequestConditions)),
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes the lease ID.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse
*
* @param options {@link BlobChangeLeaseOptions}
* @return A reactive response containing the new lease ID.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<String>> changeLeaseWithResponse(BlobChangeLeaseOptions options) {
try {
return withContext(context -> changeLeaseWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<String>> changeLeaseWithResponse(BlobChangeLeaseOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
BlobLeaseRequestConditions requestConditions = (options.getRequestConditions() == null)
? new BlobLeaseRequestConditions() : options.getRequestConditions();
context = context == null ? Context.NONE : context;
Mono<Response<String>> response;
if (this.isBlob) {
response = this.client.getBlobs().changeLeaseWithResponseAsync(containerName, blobName, this.leaseId,
options.getProposedId(), null, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(),
requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
} else {
response = this.client.getContainers().changeLeaseWithResponseAsync(containerName, this.leaseId,
options.getProposedId(), null, requestConditions.getIfModifiedSince(),
requestConditions.getIfUnmodifiedSince(), null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getXMsLeaseId()));
}
response = response.doOnSuccess(r -> this.leaseId = r.getValue());
return response;
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
} |
Given above method, why do you still use system env here? | public void testGetCertificate() throws Exception {
Security.addProvider(new KeyVaultJcaProvider());
KeyStore keystore = KeyStore.getInstance("AzureKeyVault");
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
keystore.load(parameter);
assertNotNull(keystore.getCertificate(System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME")));
} | Security.addProvider(new KeyVaultJcaProvider()); | public void testGetCertificate() throws Exception {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
Security.addProvider(new KeyVaultJcaProvider());
KeyStore keystore = KeyStore.getInstance("AzureKeyVault");
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
keystore.load(parameter);
assertNotNull(keystore.getCertificate(System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME")));
} | class KeyVaultJcaProviderTest {
public static void putEnvironmentPropertyToSystemProperty(List<String> key) {
key.forEach(
environmentPropertyKey -> {
String value = System.getenv(environmentPropertyKey);
if (value != null) {
String systemPropertyKey = environmentPropertyKey.toLowerCase().replaceFirst("azure_keyvault_",
"azure.keyvault.").replaceAll("_", "-");
System.getProperties().put(systemPropertyKey, value);
}
}
);
}
@BeforeEach
public void setEnvironmentProperty() {
putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"azure.keyvault.aad-authentication-url",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
}
/**
* Test getting a certificate using the Provider.
*
* @throws Exception when an error occurs.
*/
@Test
} | class KeyVaultJcaProviderTest {
/**
* Test getting a certificate using the Provider.
*
* @throws Exception when an error occurs.
*/
@Test
} |
same here | public void testPrivateKey() {
assertNotNull(manager.getPrivateKey(certificateName));
} | assertNotNull(manager.getPrivateKey(certificateName)); | public void testPrivateKey() {
assertNotNull(manager.getPrivateKey(certificateName));
} | class KeyVaultKeyManagerTest {
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManagerTest.class.getName());
private KeyVaultKeyManager manager;
private String certificateName;
public static void putEnvironmentPropertyToSystemProperty(List<String> key) {
key.forEach(
environmentPropertyKey -> {
String value = System.getenv(environmentPropertyKey);
if (value != null) {
String systemPropertyKey = environmentPropertyKey.toLowerCase().replaceFirst("azure_keyvault_",
"azure.keyvault.").replaceAll("_", "-");
System.getProperties().put(systemPropertyKey, value);
}
}
);
}
@BeforeEach
public void setEnvironmentProperty() throws KeyStoreException, NoSuchAlgorithmException, IOException,
CertificateException {
putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"azure.keyvault.aad-authentication-url",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
Security.insertProviderAt(new KeyVaultJcaProvider(), 1);
KeyStore keyStore = KeyStore.getInstance("AzureKeyVault");
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
keyStore.load(parameter);
manager = new KeyVaultKeyManager(keyStore, null);
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
}
@Test
@Test
public void testGetCertificateChain() {
assertNotNull(manager.getCertificateChain(certificateName));
}
} | class KeyVaultKeyManagerTest {
private static KeyVaultKeyManager manager;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() throws KeyStoreException, NoSuchAlgorithmException, IOException,
CertificateException {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
Security.insertProviderAt(new KeyVaultJcaProvider(), 1);
KeyStore keyStore = KeyStore.getInstance("AzureKeyVault");
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
keyStore.load(parameter);
manager = new KeyVaultKeyManager(keyStore, null);
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
}
@Test
@Test
public void testGetCertificateChain() {
assertNotNull(manager.getCertificateChain(certificateName));
}
} |
same here | public void testGetCertificateChain() {
assertNotNull(manager.getCertificateChain(certificateName));
} | assertNotNull(manager.getCertificateChain(certificateName)); | public void testGetCertificateChain() {
assertNotNull(manager.getCertificateChain(certificateName));
} | class KeyVaultKeyManagerTest {
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManagerTest.class.getName());
private KeyVaultKeyManager manager;
private String certificateName;
public static void putEnvironmentPropertyToSystemProperty(List<String> key) {
key.forEach(
environmentPropertyKey -> {
String value = System.getenv(environmentPropertyKey);
if (value != null) {
String systemPropertyKey = environmentPropertyKey.toLowerCase().replaceFirst("azure_keyvault_",
"azure.keyvault.").replaceAll("_", "-");
System.getProperties().put(systemPropertyKey, value);
}
}
);
}
@BeforeEach
public void setEnvironmentProperty() throws KeyStoreException, NoSuchAlgorithmException, IOException,
CertificateException {
putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"azure.keyvault.aad-authentication-url",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
Security.insertProviderAt(new KeyVaultJcaProvider(), 1);
KeyStore keyStore = KeyStore.getInstance("AzureKeyVault");
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
keyStore.load(parameter);
manager = new KeyVaultKeyManager(keyStore, null);
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
}
@Test
public void testPrivateKey() {
assertNotNull(manager.getPrivateKey(certificateName));
}
@Test
} | class KeyVaultKeyManagerTest {
private static KeyVaultKeyManager manager;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() throws KeyStoreException, NoSuchAlgorithmException, IOException,
CertificateException {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
Security.insertProviderAt(new KeyVaultJcaProvider(), 1);
KeyStore keyStore = KeyStore.getInstance("AzureKeyVault");
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
keyStore.load(parameter);
manager = new KeyVaultKeyManager(keyStore, null);
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
}
@Test
public void testPrivateKey() {
assertNotNull(manager.getPrivateKey(certificateName));
}
@Test
} |
Shall we rename cf to certificateFactory? | public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
} | CertificateFactory cf = CertificateFactory.getInstance("X.509"); | public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private KeyVaultKeyStore keystore;
private String certificateName;
public static void putEnvironmentPropertyToSystemProperty(List<String> key) {
key.forEach(
environmentPropertyKey -> {
String value = System.getenv(environmentPropertyKey);
if (value != null) {
String systemPropertyKey = environmentPropertyKey.toLowerCase().replaceFirst("azure_keyvault_",
"azure.keyvault.").replaceAll("_", "-");
System.getProperties().put(systemPropertyKey, value);
}
}
);
}
@BeforeEach
public void setEnvironmentProperty() {
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"azure.keyvault.aad-authentication-url",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineSetKeyEntry2() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} |
When will this exception be thrown? | public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
} | throw new ProviderException(e); | public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private KeyVaultKeyStore keystore;
private String certificateName;
public static void putEnvironmentPropertyToSystemProperty(List<String> key) {
key.forEach(
environmentPropertyKey -> {
String value = System.getenv(environmentPropertyKey);
if (value != null) {
String systemPropertyKey = environmentPropertyKey.toLowerCase().replaceFirst("azure_keyvault_",
"azure.keyvault.").replaceAll("_", "-");
System.getProperties().put(systemPropertyKey, value);
}
}
);
}
@BeforeEach
public void setEnvironmentProperty() {
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"azure.keyvault.aad-authentication-url",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineSetKeyEntry2() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} |
same here, please check the exact value | public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
} | assertNotNull(keystore.engineGetCertificateAlias(certificate)); | public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private KeyVaultKeyStore keystore;
private String certificateName;
public static void putEnvironmentPropertyToSystemProperty(List<String> key) {
key.forEach(
environmentPropertyKey -> {
String value = System.getenv(environmentPropertyKey);
if (value != null) {
String systemPropertyKey = environmentPropertyKey.toLowerCase().replaceFirst("azure_keyvault_",
"azure.keyvault.").replaceAll("_", "-");
System.getProperties().put(systemPropertyKey, value);
}
}
);
}
@BeforeEach
public void setEnvironmentProperty() {
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"azure.keyvault.aad-authentication-url",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineSetKeyEntry2() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} |
same here | public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
} | assertNotNull(keystore.engineGetCertificateChain(certificateName)); | public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private KeyVaultKeyStore keystore;
private String certificateName;
public static void putEnvironmentPropertyToSystemProperty(List<String> key) {
key.forEach(
environmentPropertyKey -> {
String value = System.getenv(environmentPropertyKey);
if (value != null) {
String systemPropertyKey = environmentPropertyKey.toLowerCase().replaceFirst("azure_keyvault_",
"azure.keyvault.").replaceAll("_", "-");
System.getProperties().put(systemPropertyKey, value);
}
}
);
}
@BeforeEach
public void setEnvironmentProperty() {
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"azure.keyvault.aad-authentication-url",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineSetKeyEntry2() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} |
same here | public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
} | assertNotNull(keystore.engineGetKey(certificateName, null)); | public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private KeyVaultKeyStore keystore;
private String certificateName;
public static void putEnvironmentPropertyToSystemProperty(List<String> key) {
key.forEach(
environmentPropertyKey -> {
String value = System.getenv(environmentPropertyKey);
if (value != null) {
String systemPropertyKey = environmentPropertyKey.toLowerCase().replaceFirst("azure_keyvault_",
"azure.keyvault.").replaceAll("_", "-");
System.getProperties().put(systemPropertyKey, value);
}
}
);
}
@BeforeEach
public void setEnvironmentProperty() {
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"azure.keyvault.aad-authentication-url",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineSetKeyEntry2() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} |
Can we add check here to compare the set value with exact one? Same below. | public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
} | KeyVaultKeyStore keystore = new KeyVaultKeyStore(); | public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private KeyVaultKeyStore keystore;
private String certificateName;
public static void putEnvironmentPropertyToSystemProperty(List<String> key) {
key.forEach(
environmentPropertyKey -> {
String value = System.getenv(environmentPropertyKey);
if (value != null) {
String systemPropertyKey = environmentPropertyKey.toLowerCase().replaceFirst("azure_keyvault_",
"azure.keyvault.").replaceAll("_", "-");
System.getProperties().put(systemPropertyKey, value);
}
}
);
}
@BeforeEach
public void setEnvironmentProperty() {
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"azure.keyvault.aad-authentication-url",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
@Test
public void testEngineSetKeyEntry2() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} |
This part is hard to understand. If linkHasNoCredits is successfully set to false, then hasNoCredits is true. | public void request(long request) {
if (!Operators.validate(request)) {
logger.warning("Invalid request: {}", request);
return;
}
Operators.addCap(REQUESTED, this, request);
final AmqpReceiveLink link = currentLink;
final int credits;
synchronized (creditsAdded) {
credits = getCreditsToAdd();
if (link != null && credits > 0) {
final boolean hadNoCredits = linkHasNoCredits.compareAndSet(true, false);
logger.verbose("linkName[{}] entityPath[{}] request[{}] creditsToAdd[{}] hadNoCredits[{}]"
+ " Backpressure request from downstream.",
currentLinkName, entityPath, request, credits, hadNoCredits);
if (hadNoCredits) {
link.addCredits(credits).subscribe(noop -> {
}, error -> {
logger.info("linkName[{}] was already closed. Could not add credits.", link.getLinkName());
linkHasNoCredits.compareAndSet(false, true);
});
}
} else {
logger.verbose("entityPath[{}] credits[{}] There is no link to add credits to, yet.",
entityPath, credits);
}
}
drain();
} | final boolean hadNoCredits = linkHasNoCredits.compareAndSet(true, false); | public void request(long request) {
if (!Operators.validate(request)) {
logger.warning("Invalid request: {}", request);
return;
}
Operators.addCap(REQUESTED, this, request);
addCreditsToLink("Backpressure request from downstream. Request: " + request);
drain();
} | class AmqpReceiveLinkProcessor extends FluxProcessor<AmqpReceiveLink, Message> implements Subscription {
private final ClientLogger logger = new ClientLogger(AmqpReceiveLinkProcessor.class);
private final Object lock = new Object();
private final AtomicBoolean isTerminated = new AtomicBoolean();
private final AtomicInteger retryAttempts = new AtomicInteger();
private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>();
private final AtomicBoolean linkHasNoCredits = new AtomicBoolean();
private final Object creditsAdded = new Object();
private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>();
private final AtomicInteger wip = new AtomicInteger();
private final int prefetch;
private final String entityPath;
private final Disposable parentConnection;
private final int maxQueueSize;
private volatile Throwable lastError;
private volatile boolean isCancelled;
private volatile AmqpReceiveLink currentLink;
private volatile String currentLinkName;
private volatile Disposable currentLinkSubscriptions;
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<AmqpReceiveLinkProcessor, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, Subscription.class,
"upstream");
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<AmqpReceiveLinkProcessor> REQUESTED =
AtomicLongFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, "requested");
/**
* Creates an instance of {@link AmqpReceiveLinkProcessor}.
*
* @param prefetch The number if messages to initially fetch.
* @param parentConnection Represents the parent connection.
*
* @throws NullPointerException if {@code retryPolicy} is null.
* @throws IllegalArgumentException if {@code prefetch} is less than 0.
*/
public AmqpReceiveLinkProcessor(String entityPath, int prefetch, Disposable parentConnection) {
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.parentConnection = Objects.requireNonNull(parentConnection, "'parentConnection' cannot be null.");
if (prefetch < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("'prefetch' cannot be less than 0."));
}
this.prefetch = prefetch;
this.maxQueueSize = prefetch * 2;
}
/**
* Gets the error associated with this processor.
*
* @return Error associated with this processor. {@code null} if there is no error.
*/
@Override
public Throwable getError() {
return lastError;
}
/**
* Gets whether or not the processor is terminated.
*
* @return {@code true} if the processor has terminated; false otherwise.
*/
@Override
public boolean isTerminated() {
return isTerminated.get() || isCancelled;
}
/**
* When a subscription is obtained from upstream publisher.
*
* @param subscription Subscription to upstream publisher.
*/
@Override
public void onSubscribe(Subscription subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null");
logger.info("Setting new subscription for receive link processor");
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice."));
}
requestUpstream();
}
@Override
public int getPrefetch() {
return prefetch;
}
/**
* When the next AMQP link is fetched.
*
* @param next The next AMQP receive link.
*/
@Override
public void onNext(AmqpReceiveLink next) {
Objects.requireNonNull(next, "'next' cannot be null.");
if (isTerminated()) {
logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.",
next.getLinkName(), next.getEntityPath());
Operators.onNextDropped(next, currentContext());
return;
}
final String linkName = next.getLinkName();
logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath);
final AmqpReceiveLink oldChannel;
final Disposable oldSubscription;
synchronized (lock) {
oldChannel = currentLink;
oldSubscription = currentLinkSubscriptions;
currentLink = next;
currentLinkName = next.getLinkName();
next.setEmptyCreditListener(() -> {
final int credits;
synchronized (creditsAdded) {
credits = getCreditsToAdd();
if (credits < 1) {
linkHasNoCredits.compareAndSet(false, true);
}
}
return credits;
});
currentLinkSubscriptions = Disposables.composite(
next.getEndpointStates().filter(e -> e == AmqpEndpointState.ACTIVE).next()
.flatMap(state -> {
final Mono<Void> operation;
synchronized (creditsAdded) {
final int creditsToAdd = getCreditsToAdd();
final int total = Math.max(prefetch, creditsToAdd);
logger.verbose("linkName[{}] prefetch[{}] creditsToAdd[{}] Adding initial credits.",
linkName, prefetch, creditsToAdd);
operation = next.addCredits(total);
}
return operation;
})
.subscribe(noop -> {
}, error -> logger.info("linkName[{}] was already closed. Could not add credits.", linkName)),
next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe(
state -> {
if (state == AmqpEndpointState.ACTIVE) {
logger.info("linkName[{}] credits[{}] is active.", linkName, next.getCredits());
retryAttempts.set(0);
}
},
error -> {
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
if (amqpException.getErrorCondition() == AmqpErrorCondition.LINK_STOLEN
&& amqpException.getContext() != null
&& amqpException.getContext() instanceof LinkErrorContext) {
LinkErrorContext errorContext = (LinkErrorContext) amqpException.getContext();
if (currentLink != null
&& !currentLink.getLinkName().equals(errorContext.getTrackingId())) {
logger.info("linkName[{}] entityPath[{}] trackingId[{}] Link lost signal received"
+ " for a link that is not current. Ignoring the error.",
linkName, entityPath, errorContext.getTrackingId());
return;
}
}
}
currentLink = null;
onError(error);
},
() -> {
if (parentConnection.isDisposed() || isTerminated()
|| UPSTREAM.get(this) == Operators.cancelledSubscription()) {
logger.info("linkName[{}] entityPath[{}] Terminal state reached. Disposing of link "
+ "processor.", linkName, entityPath);
dispose();
} else {
logger.info("linkName[{}] entityPath[{}] Receive link endpoint states are closed. "
+ "Requesting another.", linkName, entityPath);
final AmqpReceiveLink existing = currentLink;
currentLink = null;
currentLinkName = null;
disposeReceiver(existing);
requestUpstream();
}
}),
next.receive()
.onBackpressureBuffer(maxQueueSize, BufferOverflowStrategy.ERROR)
.subscribe(message -> {
messageQueue.add(message);
drain();
}));
}
disposeReceiver(oldChannel);
if (oldSubscription != null) {
oldSubscription.dispose();
}
}
/**
* Sets up the downstream subscriber.
*
* @param actual The downstream subscriber.
*
* @throws IllegalStateException if there is already a downstream subscriber.
*/
@Override
public void subscribe(CoreSubscriber<? super Message> actual) {
Objects.requireNonNull(actual, "'actual' cannot be null.");
final boolean terminateSubscriber = isTerminated()
|| (currentLink == null && upstream == Operators.cancelledSubscription());
if (isTerminated()) {
logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.",
currentLinkName, entityPath);
} else if (currentLink == null && upstream == Operators.cancelledSubscription()) {
logger.info("There is no current link and upstream is terminated.");
}
if (terminateSubscriber) {
actual.onSubscribe(Operators.emptySubscription());
if (hasError()) {
actual.onError(lastError);
} else {
actual.onComplete();
}
return;
}
if (downstream.compareAndSet(null, actual)) {
actual.onSubscribe(this);
drain();
} else {
Operators.error(actual, logger.logExceptionAsError(new IllegalStateException(
"There is already one downstream subscriber.'")));
}
}
/**
* When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP
* element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes.
*
* @param throwable Error that occurred in upstream publisher.
*/
@Override
public void onError(Throwable throwable) {
Objects.requireNonNull(throwable, "'throwable' is required.");
logger.info("linkName[{}] Error on receive link.", currentLinkName, throwable);
if (isTerminated() || isCancelled) {
logger.info("linkName[{}] AmqpReceiveLinkProcessor is terminated. Cannot process another error.",
currentLinkName, throwable);
Operators.onErrorDropped(throwable, currentContext());
return;
}
if (parentConnection.isDisposed()) {
logger.info("linkName[{}] Parent connection is disposed. Not reopening on error.", currentLinkName);
}
lastError = throwable;
isTerminated.set(true);
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber != null) {
subscriber.onError(throwable);
}
onDispose();
}
/**
* When the upstream publisher has no more items to emit.
*/
@Override
public void onComplete() {
logger.info("linkName[{}] Receive link completed from upstream.", currentLinkName);
UPSTREAM.set(this, Operators.cancelledSubscription());
}
@Override
public void dispose() {
if (isTerminated.getAndSet(true)) {
return;
}
logger.info("linkName[{}] Disposing receive link.", currentLinkName);
drain();
onDispose();
}
/**
* When downstream subscriber makes a back-pressure request.
*/
@Override
/**
* When downstream subscriber cancels their subscription.
*/
@Override
public void cancel() {
if (isCancelled) {
return;
}
isCancelled = true;
drain();
}
/**
* Requests another receive link from upstream.
*/
private void requestUpstream() {
if (isTerminated()) {
logger.info("Processor is terminated. Not requesting another link.");
return;
} else if (UPSTREAM.get(this) == null) {
logger.info("There is no upstream. Not requesting another link.");
return;
} else if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
logger.info("Upstream is cancelled or complete. Not requesting another link.");
return;
}
synchronized (lock) {
if (currentLink != null) {
logger.info("Current link exists. Not requesting another link.");
return;
}
}
logger.info("Requesting a new AmqpReceiveLink from upstream.");
UPSTREAM.get(this).request(1L);
}
private void onDispose() {
disposeReceiver(currentLink);
currentLink = null;
currentLinkName = null;
if (currentLinkSubscriptions != null) {
currentLinkSubscriptions.dispose();
}
Operators.onDiscardQueueWithClear(messageQueue, currentContext(), null);
}
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
drainQueue();
missed = wip.addAndGet(-missed);
}
}
private void drainQueue() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber == null || checkAndSetTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = messageQueue.isEmpty();
while (numberRequested != 0L && !isEmpty) {
if (checkAndSetTerminated()) {
break;
}
long numberEmitted = 0L;
while (numberRequested != numberEmitted) {
if (isEmpty && checkAndSetTerminated()) {
break;
}
Message message = messageQueue.poll();
if (message == null) {
break;
}
if (isCancelled) {
Operators.onDiscard(message, subscriber.currentContext());
Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null);
return;
}
try {
subscriber.onNext(message);
} catch (Exception e) {
logger.error("linkName[{}] entityPath[{}] Exception occurred while handling downstream onNext "
+ "operation.", currentLinkName, entityPath, e);
throw logger.logExceptionAsError(Exceptions.propagate(
Operators.onOperatorError(upstream, e, message, subscriber.currentContext())));
}
numberEmitted++;
isEmpty = messageQueue.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberEmitted);
}
}
if (numberRequested > 0L && isEmpty) {
synchronized (creditsAdded) {
final int creditsToAdd = getCreditsToAdd();
final AmqpReceiveLink link = currentLink;
if (link != null && creditsToAdd > 0
&& linkHasNoCredits.compareAndSet(true, false)) {
logger.verbose("linkName[{}] entityPath[{}] creditsToAdd[] Adding more credits in drain loop.",
link.getLinkName(), link.getEntityPath(), creditsToAdd);
link.addCredits(creditsToAdd).subscribe(noop -> {
}, error -> {
logger.info("linkName[{}] entityPath[{}] Unable to add credits in drain loop.",
link.getLinkName(), link.getEntityPath(), error);
linkHasNoCredits.compareAndSet(false, true);
});
}
}
}
}
private boolean checkAndSetTerminated() {
if (!isTerminated()) {
return false;
}
final CoreSubscriber<? super Message> subscriber = downstream.get();
final Throwable error = lastError;
if (error != null) {
subscriber.onError(error);
} else {
subscriber.onComplete();
}
disposeReceiver(currentLink);
messageQueue.clear();
return true;
}
private int getCreditsToAdd() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
final long request = REQUESTED.get(this);
final int credits;
if (subscriber == null || request == 0) {
credits = 0;
} else if (request == Long.MAX_VALUE) {
credits = 1;
} else {
final int remaining = Long.valueOf(request).intValue() - messageQueue.size();
credits = Math.max(remaining, 0);
}
return credits;
}
private void disposeReceiver(AmqpReceiveLink link) {
if (link == null) {
return;
}
try {
if (link instanceof AsyncAutoCloseable) {
((AsyncAutoCloseable) link).closeAsync().subscribe();
} else {
link.dispose();
}
} catch (Exception error) {
logger.warning("linkName[{}] entityPath[{}] Unable to dispose of link.", link.getLinkName(),
link.getEntityPath(), error);
}
}
} | class AmqpReceiveLinkProcessor extends FluxProcessor<AmqpReceiveLink, Message> implements Subscription {
private final ClientLogger logger = new ClientLogger(AmqpReceiveLinkProcessor.class);
private final Object lock = new Object();
private final AtomicBoolean isTerminated = new AtomicBoolean();
private final AtomicInteger retryAttempts = new AtomicInteger();
private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>();
private final AtomicBoolean linkHasNoCredits = new AtomicBoolean();
private final Object creditsAdded = new Object();
private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>();
private final AtomicInteger wip = new AtomicInteger();
private final int prefetch;
private final String entityPath;
private final Disposable parentConnection;
private final int maxQueueSize;
private volatile Throwable lastError;
private volatile boolean isCancelled;
private volatile AmqpReceiveLink currentLink;
private volatile String currentLinkName;
private volatile Disposable currentLinkSubscriptions;
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<AmqpReceiveLinkProcessor, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, Subscription.class,
"upstream");
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<AmqpReceiveLinkProcessor> REQUESTED =
AtomicLongFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, "requested");
/**
* Creates an instance of {@link AmqpReceiveLinkProcessor}.
*
* @param prefetch The number if messages to initially fetch.
* @param parentConnection Represents the parent connection.
*
* @throws NullPointerException if {@code retryPolicy} is null.
* @throws IllegalArgumentException if {@code prefetch} is less than 0.
*/
public AmqpReceiveLinkProcessor(String entityPath, int prefetch, Disposable parentConnection) {
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.parentConnection = Objects.requireNonNull(parentConnection, "'parentConnection' cannot be null.");
if (prefetch < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("'prefetch' cannot be less than 0."));
}
this.prefetch = prefetch;
this.maxQueueSize = prefetch * 2;
}
/**
* Gets the error associated with this processor.
*
* @return Error associated with this processor. {@code null} if there is no error.
*/
@Override
public Throwable getError() {
return lastError;
}
/**
* Gets whether or not the processor is terminated.
*
* @return {@code true} if the processor has terminated; false otherwise.
*/
@Override
public boolean isTerminated() {
return isTerminated.get() || isCancelled;
}
/**
* When a subscription is obtained from upstream publisher.
*
* @param subscription Subscription to upstream publisher.
*/
@Override
public void onSubscribe(Subscription subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null");
logger.info("Setting new subscription for receive link processor");
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice."));
}
requestUpstream();
}
@Override
public int getPrefetch() {
return prefetch;
}
/**
* When the next AMQP link is fetched.
*
* @param next The next AMQP receive link.
*/
@Override
public void onNext(AmqpReceiveLink next) {
Objects.requireNonNull(next, "'next' cannot be null.");
if (isTerminated()) {
logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.",
next.getLinkName(), next.getEntityPath());
Operators.onNextDropped(next, currentContext());
return;
}
final String linkName = next.getLinkName();
logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath);
final AmqpReceiveLink oldChannel;
final Disposable oldSubscription;
synchronized (lock) {
oldChannel = currentLink;
oldSubscription = currentLinkSubscriptions;
currentLink = next;
currentLinkName = next.getLinkName();
next.setEmptyCreditListener(() -> {
final int credits;
synchronized (creditsAdded) {
credits = getCreditsToAdd();
if (credits < 1) {
linkHasNoCredits.compareAndSet(false, true);
} else {
logger.info("linkName[{}] entityPath[{}] credits[{}] Link is empty. Adding more credits.",
linkName, entityPath, credits);
}
}
return credits;
});
currentLinkSubscriptions = Disposables.composite(
next.getEndpointStates().filter(e -> e == AmqpEndpointState.ACTIVE).next()
.flatMap(state -> {
final Mono<Void> operation;
synchronized (creditsAdded) {
final int creditsToAdd = getCreditsToAdd();
final int total = Math.max(prefetch, creditsToAdd);
logger.verbose("linkName[{}] prefetch[{}] creditsToAdd[{}] Adding initial credits.",
linkName, prefetch, creditsToAdd);
operation = next.addCredits(total);
}
return operation;
})
.subscribe(noop -> {
}, error -> logger.info("linkName[{}] was already closed. Could not add credits.", linkName)),
next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe(
state -> {
if (state == AmqpEndpointState.ACTIVE) {
logger.info("linkName[{}] credits[{}] is active.", linkName, next.getCredits());
retryAttempts.set(0);
}
},
error -> {
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
if (amqpException.getErrorCondition() == AmqpErrorCondition.LINK_STOLEN
&& amqpException.getContext() != null
&& amqpException.getContext() instanceof LinkErrorContext) {
LinkErrorContext errorContext = (LinkErrorContext) amqpException.getContext();
if (currentLink != null
&& !currentLink.getLinkName().equals(errorContext.getTrackingId())) {
logger.info("linkName[{}] entityPath[{}] trackingId[{}] Link lost signal received"
+ " for a link that is not current. Ignoring the error.",
linkName, entityPath, errorContext.getTrackingId());
return;
}
}
}
currentLink = null;
onError(error);
},
() -> {
if (parentConnection.isDisposed() || isTerminated()
|| UPSTREAM.get(this) == Operators.cancelledSubscription()) {
logger.info("linkName[{}] entityPath[{}] Terminal state reached. Disposing of link "
+ "processor.", linkName, entityPath);
dispose();
} else {
logger.info("linkName[{}] entityPath[{}] Receive link endpoint states are closed. "
+ "Requesting another.", linkName, entityPath);
final AmqpReceiveLink existing = currentLink;
currentLink = null;
currentLinkName = null;
disposeReceiver(existing);
requestUpstream();
}
}),
next.receive()
.onBackpressureBuffer(maxQueueSize, BufferOverflowStrategy.ERROR)
.subscribe(message -> {
messageQueue.add(message);
drain();
}));
}
disposeReceiver(oldChannel);
if (oldSubscription != null) {
oldSubscription.dispose();
}
}
/**
* Sets up the downstream subscriber.
*
* @param actual The downstream subscriber.
*
* @throws IllegalStateException if there is already a downstream subscriber.
*/
@Override
public void subscribe(CoreSubscriber<? super Message> actual) {
Objects.requireNonNull(actual, "'actual' cannot be null.");
final boolean terminateSubscriber = isTerminated()
|| (currentLink == null && upstream == Operators.cancelledSubscription());
if (isTerminated()) {
logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.",
currentLinkName, entityPath);
} else if (currentLink == null && upstream == Operators.cancelledSubscription()) {
logger.info("There is no current link and upstream is terminated.");
}
if (terminateSubscriber) {
actual.onSubscribe(Operators.emptySubscription());
if (hasError()) {
actual.onError(lastError);
} else {
actual.onComplete();
}
return;
}
if (downstream.compareAndSet(null, actual)) {
actual.onSubscribe(this);
drain();
} else {
Operators.error(actual, logger.logExceptionAsError(new IllegalStateException(
"There is already one downstream subscriber.'")));
}
}
/**
* When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP
* element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes.
*
* @param throwable Error that occurred in upstream publisher.
*/
@Override
public void onError(Throwable throwable) {
Objects.requireNonNull(throwable, "'throwable' is required.");
logger.info("linkName[{}] Error on receive link.", currentLinkName, throwable);
if (isTerminated() || isCancelled) {
logger.info("linkName[{}] AmqpReceiveLinkProcessor is terminated. Cannot process another error.",
currentLinkName, throwable);
Operators.onErrorDropped(throwable, currentContext());
return;
}
if (parentConnection.isDisposed()) {
logger.info("linkName[{}] Parent connection is disposed. Not reopening on error.", currentLinkName);
}
lastError = throwable;
isTerminated.set(true);
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber != null) {
subscriber.onError(throwable);
}
onDispose();
}
/**
* When the upstream publisher has no more items to emit.
*/
@Override
public void onComplete() {
logger.info("linkName[{}] Receive link completed from upstream.", currentLinkName);
UPSTREAM.set(this, Operators.cancelledSubscription());
}
@Override
public void dispose() {
if (isTerminated.getAndSet(true)) {
return;
}
logger.info("linkName[{}] Disposing receive link.", currentLinkName);
drain();
onDispose();
}
/**
* When downstream subscriber makes a back-pressure request.
*/
@Override
/**
* When downstream subscriber cancels their subscription.
*/
@Override
public void cancel() {
if (isCancelled) {
return;
}
isCancelled = true;
drain();
}
/**
* Requests another receive link from upstream.
*/
private void requestUpstream() {
if (isTerminated()) {
logger.info("Processor is terminated. Not requesting another link.");
return;
} else if (UPSTREAM.get(this) == null) {
logger.info("There is no upstream. Not requesting another link.");
return;
} else if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
logger.info("Upstream is cancelled or complete. Not requesting another link.");
return;
}
synchronized (lock) {
if (currentLink != null) {
logger.info("Current link exists. Not requesting another link.");
return;
}
}
logger.info("Requesting a new AmqpReceiveLink from upstream.");
UPSTREAM.get(this).request(1L);
}
private void onDispose() {
disposeReceiver(currentLink);
currentLink = null;
currentLinkName = null;
if (currentLinkSubscriptions != null) {
currentLinkSubscriptions.dispose();
}
Operators.onDiscardQueueWithClear(messageQueue, currentContext(), null);
}
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
drainQueue();
missed = wip.addAndGet(-missed);
}
}
private void drainQueue() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber == null || checkAndSetTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = messageQueue.isEmpty();
while (numberRequested != 0L && !isEmpty) {
if (checkAndSetTerminated()) {
break;
}
long numberEmitted = 0L;
while (numberRequested != numberEmitted) {
if (isEmpty && checkAndSetTerminated()) {
break;
}
Message message = messageQueue.poll();
if (message == null) {
break;
}
if (isCancelled) {
Operators.onDiscard(message, subscriber.currentContext());
Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null);
return;
}
try {
subscriber.onNext(message);
} catch (Exception e) {
logger.error("linkName[{}] entityPath[{}] Exception occurred while handling downstream onNext "
+ "operation.", currentLinkName, entityPath, e);
throw logger.logExceptionAsError(Exceptions.propagate(
Operators.onOperatorError(upstream, e, message, subscriber.currentContext())));
}
numberEmitted++;
isEmpty = messageQueue.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberEmitted);
}
}
if (numberRequested > 0L && isEmpty) {
addCreditsToLink("Adding more credits in drain loop.");
}
}
private boolean checkAndSetTerminated() {
if (!isTerminated()) {
return false;
}
final CoreSubscriber<? super Message> subscriber = downstream.get();
final Throwable error = lastError;
if (error != null) {
subscriber.onError(error);
} else {
subscriber.onComplete();
}
disposeReceiver(currentLink);
messageQueue.clear();
return true;
}
/**
* Consolidates all credits calculation when checking to see if more should be added. This is invoked in
* {@link
*
* Calculates if there are enough credits to satisfy the downstream subscriber. If there is not AND the link has no
* more credits, we will add them onto the link.
*
* In the case that the link has some credits, but _not_ enough to satisfy the request, when the link is empty, it
* will call {@link AmqpReceiveLink
*
* @param message Additional message for context.
*/
private void addCreditsToLink(String message) {
synchronized (creditsAdded) {
final AmqpReceiveLink link = currentLink;
final int credits = getCreditsToAdd();
if (link == null) {
logger.verbose("entityPath[{}] creditsToAdd[{}] There is no link to add credits to.",
entityPath, credits);
return;
}
final String linkName = link.getLinkName();
if (credits < 1) {
logger.verbose("linkName[{}] entityPath[{}] creditsToAdd[{}] There are no additional credits to add.",
linkName, entityPath, credits);
return;
}
if (linkHasNoCredits.compareAndSet(true, false)) {
logger.info("linkName[{}] entityPath[{}] creditsToAdd[{}] There are no more credits on link."
+ " Adding more. {}", linkName, entityPath, credits, message);
link.addCredits(credits).subscribe(noop -> {
}, error -> {
logger.info("linkName[{}] entityPath[{}] was already closed. Could not add credits.",
linkName, entityPath);
linkHasNoCredits.compareAndSet(false, true);
});
}
}
}
/**
* Gets the number of credits to add based on {@link
* If {@link
*
* @return The number of credits to add.
*/
private int getCreditsToAdd() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
final long request = REQUESTED.get(this);
final int credits;
if (subscriber == null || request == 0) {
credits = 0;
} else if (request == Long.MAX_VALUE) {
credits = 1;
} else {
final int remaining = Long.valueOf(request).intValue() - messageQueue.size();
credits = Math.max(remaining, 0);
}
return credits;
}
private void disposeReceiver(AmqpReceiveLink link) {
if (link == null) {
return;
}
try {
if (link instanceof AsyncAutoCloseable) {
((AsyncAutoCloseable) link).closeAsync().subscribe();
} else {
link.dispose();
}
} catch (Exception error) {
logger.warning("linkName[{}] entityPath[{}] Unable to dispose of link.", link.getLinkName(),
link.getEntityPath(), error);
}
}
} |
I created a variable so it would make it easier to log, but I really don't need the `hadNoCredits` variable. | public void request(long request) {
if (!Operators.validate(request)) {
logger.warning("Invalid request: {}", request);
return;
}
Operators.addCap(REQUESTED, this, request);
final AmqpReceiveLink link = currentLink;
final int credits;
synchronized (creditsAdded) {
credits = getCreditsToAdd();
if (link != null && credits > 0) {
final boolean hadNoCredits = linkHasNoCredits.compareAndSet(true, false);
logger.verbose("linkName[{}] entityPath[{}] request[{}] creditsToAdd[{}] hadNoCredits[{}]"
+ " Backpressure request from downstream.",
currentLinkName, entityPath, request, credits, hadNoCredits);
if (hadNoCredits) {
link.addCredits(credits).subscribe(noop -> {
}, error -> {
logger.info("linkName[{}] was already closed. Could not add credits.", link.getLinkName());
linkHasNoCredits.compareAndSet(false, true);
});
}
} else {
logger.verbose("entityPath[{}] credits[{}] There is no link to add credits to, yet.",
entityPath, credits);
}
}
drain();
} | final boolean hadNoCredits = linkHasNoCredits.compareAndSet(true, false); | public void request(long request) {
if (!Operators.validate(request)) {
logger.warning("Invalid request: {}", request);
return;
}
Operators.addCap(REQUESTED, this, request);
addCreditsToLink("Backpressure request from downstream. Request: " + request);
drain();
} | class AmqpReceiveLinkProcessor extends FluxProcessor<AmqpReceiveLink, Message> implements Subscription {
private final ClientLogger logger = new ClientLogger(AmqpReceiveLinkProcessor.class);
private final Object lock = new Object();
private final AtomicBoolean isTerminated = new AtomicBoolean();
private final AtomicInteger retryAttempts = new AtomicInteger();
private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>();
private final AtomicBoolean linkHasNoCredits = new AtomicBoolean();
private final Object creditsAdded = new Object();
private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>();
private final AtomicInteger wip = new AtomicInteger();
private final int prefetch;
private final String entityPath;
private final Disposable parentConnection;
private final int maxQueueSize;
private volatile Throwable lastError;
private volatile boolean isCancelled;
private volatile AmqpReceiveLink currentLink;
private volatile String currentLinkName;
private volatile Disposable currentLinkSubscriptions;
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<AmqpReceiveLinkProcessor, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, Subscription.class,
"upstream");
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<AmqpReceiveLinkProcessor> REQUESTED =
AtomicLongFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, "requested");
/**
* Creates an instance of {@link AmqpReceiveLinkProcessor}.
*
* @param prefetch The number if messages to initially fetch.
* @param parentConnection Represents the parent connection.
*
* @throws NullPointerException if {@code retryPolicy} is null.
* @throws IllegalArgumentException if {@code prefetch} is less than 0.
*/
public AmqpReceiveLinkProcessor(String entityPath, int prefetch, Disposable parentConnection) {
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.parentConnection = Objects.requireNonNull(parentConnection, "'parentConnection' cannot be null.");
if (prefetch < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("'prefetch' cannot be less than 0."));
}
this.prefetch = prefetch;
this.maxQueueSize = prefetch * 2;
}
/**
* Gets the error associated with this processor.
*
* @return Error associated with this processor. {@code null} if there is no error.
*/
@Override
public Throwable getError() {
return lastError;
}
/**
* Gets whether or not the processor is terminated.
*
* @return {@code true} if the processor has terminated; false otherwise.
*/
@Override
public boolean isTerminated() {
return isTerminated.get() || isCancelled;
}
/**
* When a subscription is obtained from upstream publisher.
*
* @param subscription Subscription to upstream publisher.
*/
@Override
public void onSubscribe(Subscription subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null");
logger.info("Setting new subscription for receive link processor");
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice."));
}
requestUpstream();
}
@Override
public int getPrefetch() {
return prefetch;
}
/**
* When the next AMQP link is fetched.
*
* @param next The next AMQP receive link.
*/
@Override
public void onNext(AmqpReceiveLink next) {
Objects.requireNonNull(next, "'next' cannot be null.");
if (isTerminated()) {
logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.",
next.getLinkName(), next.getEntityPath());
Operators.onNextDropped(next, currentContext());
return;
}
final String linkName = next.getLinkName();
logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath);
final AmqpReceiveLink oldChannel;
final Disposable oldSubscription;
synchronized (lock) {
oldChannel = currentLink;
oldSubscription = currentLinkSubscriptions;
currentLink = next;
currentLinkName = next.getLinkName();
next.setEmptyCreditListener(() -> {
final int credits;
synchronized (creditsAdded) {
credits = getCreditsToAdd();
if (credits < 1) {
linkHasNoCredits.compareAndSet(false, true);
}
}
return credits;
});
currentLinkSubscriptions = Disposables.composite(
next.getEndpointStates().filter(e -> e == AmqpEndpointState.ACTIVE).next()
.flatMap(state -> {
final Mono<Void> operation;
synchronized (creditsAdded) {
final int creditsToAdd = getCreditsToAdd();
final int total = Math.max(prefetch, creditsToAdd);
logger.verbose("linkName[{}] prefetch[{}] creditsToAdd[{}] Adding initial credits.",
linkName, prefetch, creditsToAdd);
operation = next.addCredits(total);
}
return operation;
})
.subscribe(noop -> {
}, error -> logger.info("linkName[{}] was already closed. Could not add credits.", linkName)),
next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe(
state -> {
if (state == AmqpEndpointState.ACTIVE) {
logger.info("linkName[{}] credits[{}] is active.", linkName, next.getCredits());
retryAttempts.set(0);
}
},
error -> {
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
if (amqpException.getErrorCondition() == AmqpErrorCondition.LINK_STOLEN
&& amqpException.getContext() != null
&& amqpException.getContext() instanceof LinkErrorContext) {
LinkErrorContext errorContext = (LinkErrorContext) amqpException.getContext();
if (currentLink != null
&& !currentLink.getLinkName().equals(errorContext.getTrackingId())) {
logger.info("linkName[{}] entityPath[{}] trackingId[{}] Link lost signal received"
+ " for a link that is not current. Ignoring the error.",
linkName, entityPath, errorContext.getTrackingId());
return;
}
}
}
currentLink = null;
onError(error);
},
() -> {
if (parentConnection.isDisposed() || isTerminated()
|| UPSTREAM.get(this) == Operators.cancelledSubscription()) {
logger.info("linkName[{}] entityPath[{}] Terminal state reached. Disposing of link "
+ "processor.", linkName, entityPath);
dispose();
} else {
logger.info("linkName[{}] entityPath[{}] Receive link endpoint states are closed. "
+ "Requesting another.", linkName, entityPath);
final AmqpReceiveLink existing = currentLink;
currentLink = null;
currentLinkName = null;
disposeReceiver(existing);
requestUpstream();
}
}),
next.receive()
.onBackpressureBuffer(maxQueueSize, BufferOverflowStrategy.ERROR)
.subscribe(message -> {
messageQueue.add(message);
drain();
}));
}
disposeReceiver(oldChannel);
if (oldSubscription != null) {
oldSubscription.dispose();
}
}
/**
* Sets up the downstream subscriber.
*
* @param actual The downstream subscriber.
*
* @throws IllegalStateException if there is already a downstream subscriber.
*/
@Override
public void subscribe(CoreSubscriber<? super Message> actual) {
Objects.requireNonNull(actual, "'actual' cannot be null.");
final boolean terminateSubscriber = isTerminated()
|| (currentLink == null && upstream == Operators.cancelledSubscription());
if (isTerminated()) {
logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.",
currentLinkName, entityPath);
} else if (currentLink == null && upstream == Operators.cancelledSubscription()) {
logger.info("There is no current link and upstream is terminated.");
}
if (terminateSubscriber) {
actual.onSubscribe(Operators.emptySubscription());
if (hasError()) {
actual.onError(lastError);
} else {
actual.onComplete();
}
return;
}
if (downstream.compareAndSet(null, actual)) {
actual.onSubscribe(this);
drain();
} else {
Operators.error(actual, logger.logExceptionAsError(new IllegalStateException(
"There is already one downstream subscriber.'")));
}
}
/**
* When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP
* element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes.
*
* @param throwable Error that occurred in upstream publisher.
*/
@Override
public void onError(Throwable throwable) {
Objects.requireNonNull(throwable, "'throwable' is required.");
logger.info("linkName[{}] Error on receive link.", currentLinkName, throwable);
if (isTerminated() || isCancelled) {
logger.info("linkName[{}] AmqpReceiveLinkProcessor is terminated. Cannot process another error.",
currentLinkName, throwable);
Operators.onErrorDropped(throwable, currentContext());
return;
}
if (parentConnection.isDisposed()) {
logger.info("linkName[{}] Parent connection is disposed. Not reopening on error.", currentLinkName);
}
lastError = throwable;
isTerminated.set(true);
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber != null) {
subscriber.onError(throwable);
}
onDispose();
}
/**
* When the upstream publisher has no more items to emit.
*/
@Override
public void onComplete() {
logger.info("linkName[{}] Receive link completed from upstream.", currentLinkName);
UPSTREAM.set(this, Operators.cancelledSubscription());
}
@Override
public void dispose() {
if (isTerminated.getAndSet(true)) {
return;
}
logger.info("linkName[{}] Disposing receive link.", currentLinkName);
drain();
onDispose();
}
/**
* When downstream subscriber makes a back-pressure request.
*/
@Override
/**
* When downstream subscriber cancels their subscription.
*/
@Override
public void cancel() {
if (isCancelled) {
return;
}
isCancelled = true;
drain();
}
/**
* Requests another receive link from upstream.
*/
private void requestUpstream() {
if (isTerminated()) {
logger.info("Processor is terminated. Not requesting another link.");
return;
} else if (UPSTREAM.get(this) == null) {
logger.info("There is no upstream. Not requesting another link.");
return;
} else if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
logger.info("Upstream is cancelled or complete. Not requesting another link.");
return;
}
synchronized (lock) {
if (currentLink != null) {
logger.info("Current link exists. Not requesting another link.");
return;
}
}
logger.info("Requesting a new AmqpReceiveLink from upstream.");
UPSTREAM.get(this).request(1L);
}
private void onDispose() {
disposeReceiver(currentLink);
currentLink = null;
currentLinkName = null;
if (currentLinkSubscriptions != null) {
currentLinkSubscriptions.dispose();
}
Operators.onDiscardQueueWithClear(messageQueue, currentContext(), null);
}
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
drainQueue();
missed = wip.addAndGet(-missed);
}
}
private void drainQueue() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber == null || checkAndSetTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = messageQueue.isEmpty();
while (numberRequested != 0L && !isEmpty) {
if (checkAndSetTerminated()) {
break;
}
long numberEmitted = 0L;
while (numberRequested != numberEmitted) {
if (isEmpty && checkAndSetTerminated()) {
break;
}
Message message = messageQueue.poll();
if (message == null) {
break;
}
if (isCancelled) {
Operators.onDiscard(message, subscriber.currentContext());
Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null);
return;
}
try {
subscriber.onNext(message);
} catch (Exception e) {
logger.error("linkName[{}] entityPath[{}] Exception occurred while handling downstream onNext "
+ "operation.", currentLinkName, entityPath, e);
throw logger.logExceptionAsError(Exceptions.propagate(
Operators.onOperatorError(upstream, e, message, subscriber.currentContext())));
}
numberEmitted++;
isEmpty = messageQueue.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberEmitted);
}
}
if (numberRequested > 0L && isEmpty) {
synchronized (creditsAdded) {
final int creditsToAdd = getCreditsToAdd();
final AmqpReceiveLink link = currentLink;
if (link != null && creditsToAdd > 0
&& linkHasNoCredits.compareAndSet(true, false)) {
logger.verbose("linkName[{}] entityPath[{}] creditsToAdd[] Adding more credits in drain loop.",
link.getLinkName(), link.getEntityPath(), creditsToAdd);
link.addCredits(creditsToAdd).subscribe(noop -> {
}, error -> {
logger.info("linkName[{}] entityPath[{}] Unable to add credits in drain loop.",
link.getLinkName(), link.getEntityPath(), error);
linkHasNoCredits.compareAndSet(false, true);
});
}
}
}
}
private boolean checkAndSetTerminated() {
if (!isTerminated()) {
return false;
}
final CoreSubscriber<? super Message> subscriber = downstream.get();
final Throwable error = lastError;
if (error != null) {
subscriber.onError(error);
} else {
subscriber.onComplete();
}
disposeReceiver(currentLink);
messageQueue.clear();
return true;
}
private int getCreditsToAdd() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
final long request = REQUESTED.get(this);
final int credits;
if (subscriber == null || request == 0) {
credits = 0;
} else if (request == Long.MAX_VALUE) {
credits = 1;
} else {
final int remaining = Long.valueOf(request).intValue() - messageQueue.size();
credits = Math.max(remaining, 0);
}
return credits;
}
private void disposeReceiver(AmqpReceiveLink link) {
if (link == null) {
return;
}
try {
if (link instanceof AsyncAutoCloseable) {
((AsyncAutoCloseable) link).closeAsync().subscribe();
} else {
link.dispose();
}
} catch (Exception error) {
logger.warning("linkName[{}] entityPath[{}] Unable to dispose of link.", link.getLinkName(),
link.getEntityPath(), error);
}
}
} | class AmqpReceiveLinkProcessor extends FluxProcessor<AmqpReceiveLink, Message> implements Subscription {
private final ClientLogger logger = new ClientLogger(AmqpReceiveLinkProcessor.class);
private final Object lock = new Object();
private final AtomicBoolean isTerminated = new AtomicBoolean();
private final AtomicInteger retryAttempts = new AtomicInteger();
private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>();
private final AtomicBoolean linkHasNoCredits = new AtomicBoolean();
private final Object creditsAdded = new Object();
private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>();
private final AtomicInteger wip = new AtomicInteger();
private final int prefetch;
private final String entityPath;
private final Disposable parentConnection;
private final int maxQueueSize;
private volatile Throwable lastError;
private volatile boolean isCancelled;
private volatile AmqpReceiveLink currentLink;
private volatile String currentLinkName;
private volatile Disposable currentLinkSubscriptions;
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<AmqpReceiveLinkProcessor, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, Subscription.class,
"upstream");
/**
* The number of requested messages.
*/
private volatile long requested;
private static final AtomicLongFieldUpdater<AmqpReceiveLinkProcessor> REQUESTED =
AtomicLongFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, "requested");
/**
* Creates an instance of {@link AmqpReceiveLinkProcessor}.
*
* @param prefetch The number if messages to initially fetch.
* @param parentConnection Represents the parent connection.
*
* @throws NullPointerException if {@code retryPolicy} is null.
* @throws IllegalArgumentException if {@code prefetch} is less than 0.
*/
public AmqpReceiveLinkProcessor(String entityPath, int prefetch, Disposable parentConnection) {
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.parentConnection = Objects.requireNonNull(parentConnection, "'parentConnection' cannot be null.");
if (prefetch < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("'prefetch' cannot be less than 0."));
}
this.prefetch = prefetch;
this.maxQueueSize = prefetch * 2;
}
/**
* Gets the error associated with this processor.
*
* @return Error associated with this processor. {@code null} if there is no error.
*/
@Override
public Throwable getError() {
return lastError;
}
/**
* Gets whether or not the processor is terminated.
*
* @return {@code true} if the processor has terminated; false otherwise.
*/
@Override
public boolean isTerminated() {
return isTerminated.get() || isCancelled;
}
/**
* When a subscription is obtained from upstream publisher.
*
* @param subscription Subscription to upstream publisher.
*/
@Override
public void onSubscribe(Subscription subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null");
logger.info("Setting new subscription for receive link processor");
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice."));
}
requestUpstream();
}
@Override
public int getPrefetch() {
return prefetch;
}
/**
* When the next AMQP link is fetched.
*
* @param next The next AMQP receive link.
*/
@Override
public void onNext(AmqpReceiveLink next) {
Objects.requireNonNull(next, "'next' cannot be null.");
if (isTerminated()) {
logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.",
next.getLinkName(), next.getEntityPath());
Operators.onNextDropped(next, currentContext());
return;
}
final String linkName = next.getLinkName();
logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath);
final AmqpReceiveLink oldChannel;
final Disposable oldSubscription;
synchronized (lock) {
oldChannel = currentLink;
oldSubscription = currentLinkSubscriptions;
currentLink = next;
currentLinkName = next.getLinkName();
next.setEmptyCreditListener(() -> {
final int credits;
synchronized (creditsAdded) {
credits = getCreditsToAdd();
if (credits < 1) {
linkHasNoCredits.compareAndSet(false, true);
} else {
logger.info("linkName[{}] entityPath[{}] credits[{}] Link is empty. Adding more credits.",
linkName, entityPath, credits);
}
}
return credits;
});
currentLinkSubscriptions = Disposables.composite(
next.getEndpointStates().filter(e -> e == AmqpEndpointState.ACTIVE).next()
.flatMap(state -> {
final Mono<Void> operation;
synchronized (creditsAdded) {
final int creditsToAdd = getCreditsToAdd();
final int total = Math.max(prefetch, creditsToAdd);
logger.verbose("linkName[{}] prefetch[{}] creditsToAdd[{}] Adding initial credits.",
linkName, prefetch, creditsToAdd);
operation = next.addCredits(total);
}
return operation;
})
.subscribe(noop -> {
}, error -> logger.info("linkName[{}] was already closed. Could not add credits.", linkName)),
next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe(
state -> {
if (state == AmqpEndpointState.ACTIVE) {
logger.info("linkName[{}] credits[{}] is active.", linkName, next.getCredits());
retryAttempts.set(0);
}
},
error -> {
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
if (amqpException.getErrorCondition() == AmqpErrorCondition.LINK_STOLEN
&& amqpException.getContext() != null
&& amqpException.getContext() instanceof LinkErrorContext) {
LinkErrorContext errorContext = (LinkErrorContext) amqpException.getContext();
if (currentLink != null
&& !currentLink.getLinkName().equals(errorContext.getTrackingId())) {
logger.info("linkName[{}] entityPath[{}] trackingId[{}] Link lost signal received"
+ " for a link that is not current. Ignoring the error.",
linkName, entityPath, errorContext.getTrackingId());
return;
}
}
}
currentLink = null;
onError(error);
},
() -> {
if (parentConnection.isDisposed() || isTerminated()
|| UPSTREAM.get(this) == Operators.cancelledSubscription()) {
logger.info("linkName[{}] entityPath[{}] Terminal state reached. Disposing of link "
+ "processor.", linkName, entityPath);
dispose();
} else {
logger.info("linkName[{}] entityPath[{}] Receive link endpoint states are closed. "
+ "Requesting another.", linkName, entityPath);
final AmqpReceiveLink existing = currentLink;
currentLink = null;
currentLinkName = null;
disposeReceiver(existing);
requestUpstream();
}
}),
next.receive()
.onBackpressureBuffer(maxQueueSize, BufferOverflowStrategy.ERROR)
.subscribe(message -> {
messageQueue.add(message);
drain();
}));
}
disposeReceiver(oldChannel);
if (oldSubscription != null) {
oldSubscription.dispose();
}
}
/**
* Sets up the downstream subscriber.
*
* @param actual The downstream subscriber.
*
* @throws IllegalStateException if there is already a downstream subscriber.
*/
@Override
public void subscribe(CoreSubscriber<? super Message> actual) {
Objects.requireNonNull(actual, "'actual' cannot be null.");
final boolean terminateSubscriber = isTerminated()
|| (currentLink == null && upstream == Operators.cancelledSubscription());
if (isTerminated()) {
logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.",
currentLinkName, entityPath);
} else if (currentLink == null && upstream == Operators.cancelledSubscription()) {
logger.info("There is no current link and upstream is terminated.");
}
if (terminateSubscriber) {
actual.onSubscribe(Operators.emptySubscription());
if (hasError()) {
actual.onError(lastError);
} else {
actual.onComplete();
}
return;
}
if (downstream.compareAndSet(null, actual)) {
actual.onSubscribe(this);
drain();
} else {
Operators.error(actual, logger.logExceptionAsError(new IllegalStateException(
"There is already one downstream subscriber.'")));
}
}
/**
* When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP
* element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes.
*
* @param throwable Error that occurred in upstream publisher.
*/
@Override
public void onError(Throwable throwable) {
Objects.requireNonNull(throwable, "'throwable' is required.");
logger.info("linkName[{}] Error on receive link.", currentLinkName, throwable);
if (isTerminated() || isCancelled) {
logger.info("linkName[{}] AmqpReceiveLinkProcessor is terminated. Cannot process another error.",
currentLinkName, throwable);
Operators.onErrorDropped(throwable, currentContext());
return;
}
if (parentConnection.isDisposed()) {
logger.info("linkName[{}] Parent connection is disposed. Not reopening on error.", currentLinkName);
}
lastError = throwable;
isTerminated.set(true);
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber != null) {
subscriber.onError(throwable);
}
onDispose();
}
/**
* When the upstream publisher has no more items to emit.
*/
@Override
public void onComplete() {
logger.info("linkName[{}] Receive link completed from upstream.", currentLinkName);
UPSTREAM.set(this, Operators.cancelledSubscription());
}
@Override
public void dispose() {
if (isTerminated.getAndSet(true)) {
return;
}
logger.info("linkName[{}] Disposing receive link.", currentLinkName);
drain();
onDispose();
}
/**
* When downstream subscriber makes a back-pressure request.
*/
@Override
/**
* When downstream subscriber cancels their subscription.
*/
@Override
public void cancel() {
if (isCancelled) {
return;
}
isCancelled = true;
drain();
}
/**
* Requests another receive link from upstream.
*/
private void requestUpstream() {
if (isTerminated()) {
logger.info("Processor is terminated. Not requesting another link.");
return;
} else if (UPSTREAM.get(this) == null) {
logger.info("There is no upstream. Not requesting another link.");
return;
} else if (UPSTREAM.get(this) == Operators.cancelledSubscription()) {
logger.info("Upstream is cancelled or complete. Not requesting another link.");
return;
}
synchronized (lock) {
if (currentLink != null) {
logger.info("Current link exists. Not requesting another link.");
return;
}
}
logger.info("Requesting a new AmqpReceiveLink from upstream.");
UPSTREAM.get(this).request(1L);
}
private void onDispose() {
disposeReceiver(currentLink);
currentLink = null;
currentLinkName = null;
if (currentLinkSubscriptions != null) {
currentLinkSubscriptions.dispose();
}
Operators.onDiscardQueueWithClear(messageQueue, currentContext(), null);
}
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
drainQueue();
missed = wip.addAndGet(-missed);
}
}
private void drainQueue() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber == null || checkAndSetTerminated()) {
return;
}
long numberRequested = REQUESTED.get(this);
boolean isEmpty = messageQueue.isEmpty();
while (numberRequested != 0L && !isEmpty) {
if (checkAndSetTerminated()) {
break;
}
long numberEmitted = 0L;
while (numberRequested != numberEmitted) {
if (isEmpty && checkAndSetTerminated()) {
break;
}
Message message = messageQueue.poll();
if (message == null) {
break;
}
if (isCancelled) {
Operators.onDiscard(message, subscriber.currentContext());
Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null);
return;
}
try {
subscriber.onNext(message);
} catch (Exception e) {
logger.error("linkName[{}] entityPath[{}] Exception occurred while handling downstream onNext "
+ "operation.", currentLinkName, entityPath, e);
throw logger.logExceptionAsError(Exceptions.propagate(
Operators.onOperatorError(upstream, e, message, subscriber.currentContext())));
}
numberEmitted++;
isEmpty = messageQueue.isEmpty();
}
final long requestedMessages = REQUESTED.get(this);
if (requestedMessages != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberEmitted);
}
}
if (numberRequested > 0L && isEmpty) {
addCreditsToLink("Adding more credits in drain loop.");
}
}
private boolean checkAndSetTerminated() {
if (!isTerminated()) {
return false;
}
final CoreSubscriber<? super Message> subscriber = downstream.get();
final Throwable error = lastError;
if (error != null) {
subscriber.onError(error);
} else {
subscriber.onComplete();
}
disposeReceiver(currentLink);
messageQueue.clear();
return true;
}
/**
* Consolidates all credits calculation when checking to see if more should be added. This is invoked in
* {@link
*
* Calculates if there are enough credits to satisfy the downstream subscriber. If there is not AND the link has no
* more credits, we will add them onto the link.
*
* In the case that the link has some credits, but _not_ enough to satisfy the request, when the link is empty, it
* will call {@link AmqpReceiveLink
*
* @param message Additional message for context.
*/
private void addCreditsToLink(String message) {
synchronized (creditsAdded) {
final AmqpReceiveLink link = currentLink;
final int credits = getCreditsToAdd();
if (link == null) {
logger.verbose("entityPath[{}] creditsToAdd[{}] There is no link to add credits to.",
entityPath, credits);
return;
}
final String linkName = link.getLinkName();
if (credits < 1) {
logger.verbose("linkName[{}] entityPath[{}] creditsToAdd[{}] There are no additional credits to add.",
linkName, entityPath, credits);
return;
}
if (linkHasNoCredits.compareAndSet(true, false)) {
logger.info("linkName[{}] entityPath[{}] creditsToAdd[{}] There are no more credits on link."
+ " Adding more. {}", linkName, entityPath, credits, message);
link.addCredits(credits).subscribe(noop -> {
}, error -> {
logger.info("linkName[{}] entityPath[{}] was already closed. Could not add credits.",
linkName, entityPath);
linkHasNoCredits.compareAndSet(false, true);
});
}
}
}
/**
* Gets the number of credits to add based on {@link
* If {@link
*
* @return The number of credits to add.
*/
private int getCreditsToAdd() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
final long request = REQUESTED.get(this);
final int credits;
if (subscriber == null || request == 0) {
credits = 0;
} else if (request == Long.MAX_VALUE) {
credits = 1;
} else {
final int remaining = Long.valueOf(request).intValue() - messageQueue.size();
credits = Math.max(remaining, 0);
}
return credits;
}
private void disposeReceiver(AmqpReceiveLink link) {
if (link == null) {
return;
}
try {
if (link instanceof AsyncAutoCloseable) {
((AsyncAutoCloseable) link).closeAsync().subscribe();
} else {
link.dispose();
}
} catch (Exception error) {
logger.warning("linkName[{}] entityPath[{}] Unable to dispose of link.", link.getLinkName(),
link.getEntityPath(), error);
}
}
} |
Should we also add this fix to getFileClient? So customers can get references to files in the root dir | public ShareDirectoryAsyncClient getSubdirectoryClient(String subdirectoryName) {
StringBuilder directoryPathBuilder = new StringBuilder()
.append(this.directoryPath);
if (!this.directoryPath.isEmpty() && !this.directoryPath.endsWith("/")) {
directoryPathBuilder.append("/");
}
directoryPathBuilder.append(subdirectoryName);
return new ShareDirectoryAsyncClient(azureFileStorageClient, shareName, directoryPathBuilder.toString(),
snapshot, accountName, serviceVersion);
} | StringBuilder directoryPathBuilder = new StringBuilder() | public ShareDirectoryAsyncClient getSubdirectoryClient(String subdirectoryName) {
StringBuilder directoryPathBuilder = new StringBuilder()
.append(this.directoryPath);
if (!this.directoryPath.isEmpty() && !this.directoryPath.endsWith("/")) {
directoryPathBuilder.append("/");
}
directoryPathBuilder.append(subdirectoryName);
return new ShareDirectoryAsyncClient(azureFileStorageClient, shareName, directoryPathBuilder.toString(),
snapshot, accountName, serviceVersion);
} | class ShareDirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareDirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
private final ShareServiceVersion serviceVersion;
/**
* Creates a ShareDirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
ShareDirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName, ShareServiceVersion serviceVersion) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
this.serviceVersion = serviceVersion;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?sharesnapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public ShareServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Constructs a ShareFileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link ShareFileAsyncClient | class ShareDirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareDirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
private final ShareServiceVersion serviceVersion;
/**
* Creates a ShareDirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
ShareDirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName, ShareServiceVersion serviceVersion) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
this.serviceVersion = serviceVersion;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?sharesnapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public ShareServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Constructs a ShareFileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link ShareFileAsyncClient |
It looks like getFileClient already has support for root directory clients, though they have a bit of a simpler solution than a StringBuilder | public ShareDirectoryAsyncClient getSubdirectoryClient(String subdirectoryName) {
StringBuilder directoryPathBuilder = new StringBuilder()
.append(this.directoryPath);
if (!this.directoryPath.isEmpty() && !this.directoryPath.endsWith("/")) {
directoryPathBuilder.append("/");
}
directoryPathBuilder.append(subdirectoryName);
return new ShareDirectoryAsyncClient(azureFileStorageClient, shareName, directoryPathBuilder.toString(),
snapshot, accountName, serviceVersion);
} | StringBuilder directoryPathBuilder = new StringBuilder() | public ShareDirectoryAsyncClient getSubdirectoryClient(String subdirectoryName) {
StringBuilder directoryPathBuilder = new StringBuilder()
.append(this.directoryPath);
if (!this.directoryPath.isEmpty() && !this.directoryPath.endsWith("/")) {
directoryPathBuilder.append("/");
}
directoryPathBuilder.append(subdirectoryName);
return new ShareDirectoryAsyncClient(azureFileStorageClient, shareName, directoryPathBuilder.toString(),
snapshot, accountName, serviceVersion);
} | class ShareDirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareDirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
private final ShareServiceVersion serviceVersion;
/**
* Creates a ShareDirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
ShareDirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName, ShareServiceVersion serviceVersion) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
this.serviceVersion = serviceVersion;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?sharesnapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public ShareServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Constructs a ShareFileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link ShareFileAsyncClient | class ShareDirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareDirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
private final ShareServiceVersion serviceVersion;
/**
* Creates a ShareDirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
ShareDirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName, ShareServiceVersion serviceVersion) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
this.serviceVersion = serviceVersion;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?sharesnapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public ShareServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Constructs a ShareFileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link ShareFileAsyncClient |
will this NPE if directoryName is null? | public ShareDirectoryAsyncClient getDirectoryClient(String directoryName) {
directoryName = directoryName.equals("/")
? ""
: directoryName;
return new ShareDirectoryAsyncClient(azureFileStorageClient, shareName, directoryName, snapshot, accountName,
serviceVersion);
} | directoryName = directoryName.equals("/") | public ShareDirectoryAsyncClient getDirectoryClient(String directoryName) {
directoryName = "/".equals(directoryName)
? ""
: directoryName;
return new ShareDirectoryAsyncClient(azureFileStorageClient, shareName, directoryName, snapshot, accountName,
serviceVersion);
} | class ShareAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String snapshot;
private final String accountName;
private final ShareServiceVersion serviceVersion;
/**
* Creates a ShareAsyncClient that sends requests to the storage share at {@link AzureFileStorageImpl
* endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the
* {@code azureFileStorageClient}.
*
* @param client Client that interacts with the service interfaces
* @param shareName Name of the share
*/
ShareAsyncClient(AzureFileStorageImpl client, String shareName, String snapshot, String accountName,
ShareServiceVersion serviceVersion) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
this.shareName = shareName;
this.snapshot = snapshot;
this.accountName = accountName;
this.azureFileStorageClient = client;
this.serviceVersion = serviceVersion;
}
/**
* Get the url of the storage account.
*
* @return the URL of the storage account
*/
public String getAccountUrl() {
return azureFileStorageClient.getUrl();
}
/**
* Get the url of the storage share client.
*
* @return the url of the Storage Share.
*/
public String getShareUrl() {
StringBuilder shareUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/").append(shareName);
if (snapshot != null) {
shareUrlString.append("?sharesnapshot=").append(snapshot);
}
return shareUrlString.toString();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public ShareServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Constructs a {@link ShareDirectoryAsyncClient} that interacts with the root directory in the share.
*
* <p>If the directory doesn't exist in the share {@link ShareDirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @return a {@link ShareDirectoryAsyncClient} that interacts with the root directory in the share
*/
public ShareDirectoryAsyncClient getRootDirectoryClient() {
return getDirectoryClient("");
}
/**
* Constructs a {@link ShareDirectoryAsyncClient} that interacts with the specified directory.
*
* <p>If the directory doesn't exist in the share {@link ShareDirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @param directoryName Name of the directory
* @return a {@link ShareDirectoryAsyncClient} that interacts with the directory in the share
*/
/**
* Constructs a {@link ShareFileAsyncClient} that interacts with the specified file.
*
* <p>If the file doesn't exist in the share {@link ShareFileAsyncClient | class ShareAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String snapshot;
private final String accountName;
private final ShareServiceVersion serviceVersion;
/**
* Creates a ShareAsyncClient that sends requests to the storage share at {@link AzureFileStorageImpl
* endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the
* {@code azureFileStorageClient}.
*
* @param client Client that interacts with the service interfaces
* @param shareName Name of the share
*/
ShareAsyncClient(AzureFileStorageImpl client, String shareName, String snapshot, String accountName,
ShareServiceVersion serviceVersion) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
this.shareName = shareName;
this.snapshot = snapshot;
this.accountName = accountName;
this.azureFileStorageClient = client;
this.serviceVersion = serviceVersion;
}
/**
* Get the url of the storage account.
*
* @return the URL of the storage account
*/
public String getAccountUrl() {
return azureFileStorageClient.getUrl();
}
/**
* Get the url of the storage share client.
*
* @return the url of the Storage Share.
*/
public String getShareUrl() {
StringBuilder shareUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/").append(shareName);
if (snapshot != null) {
shareUrlString.append("?sharesnapshot=").append(snapshot);
}
return shareUrlString.toString();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public ShareServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Constructs a {@link ShareDirectoryAsyncClient} that interacts with the root directory in the share.
*
* <p>If the directory doesn't exist in the share {@link ShareDirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @return a {@link ShareDirectoryAsyncClient} that interacts with the root directory in the share
*/
public ShareDirectoryAsyncClient getRootDirectoryClient() {
return getDirectoryClient("");
}
/**
* Constructs a {@link ShareDirectoryAsyncClient} that interacts with the specified directory.
*
* <p>If the directory doesn't exist in the share {@link ShareDirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @param directoryName Name of the directory
* @return a {@link ShareDirectoryAsyncClient} that interacts with the directory in the share
*/
/**
* Constructs a {@link ShareFileAsyncClient} that interacts with the specified file.
*
* <p>If the file doesn't exist in the share {@link ShareFileAsyncClient |
endpoint is a URL, it is possible that it also contains subpath, can we only override port value for the endpoint? | public WebPubSubAsyncServiceClient buildAsyncClient() {
if (hub == null || hub.isEmpty()) {
logger.logThrowableAsError(
new IllegalStateException("hub is not valid - it must be non-null and non-empty."));
}
if (endpoint == null && credential == null) {
final Map<String, String> csParams = parseConnectionString(connectionString);
if (!csParams.containsKey("endpoint") && !csParams.containsKey("accesskey")) {
logger.logThrowableAsError(new IllegalArgumentException(
"Connection string does not contain required 'endpoint' and 'accesskey' values"));
}
final String accessKey = csParams.get("accesskey");
this.credential = new AzureKeyCredential(accessKey);
this.endpoint = csParams.get("endpoint");
String port = csParams.get("port");
if (!CoreUtils.isNullOrEmpty(port)) {
this.endpoint = this.endpoint + ":" + port;
}
}
final AzureWebPubSubServiceRestAPIImplBuilder innerBuilder = new AzureWebPubSubServiceRestAPIImplBuilder();
if (endpoint == null || endpoint.isEmpty()) {
logger.logThrowableAsError(
new IllegalStateException("endpoint is not valid - it must be non-null and non-empty."));
}
innerBuilder.host(endpoint);
final WebPubSubServiceVersion serviceVersion =
version != null ? version : WebPubSubServiceVersion.getLatest();
WebPubSubAuthenticationPolicy webPubSubAuthPolicy = new WebPubSubAuthenticationPolicy(credential);
if (pipeline != null) {
innerBuilder.pipeline(pipeline);
return buildAsyncClient(innerBuilder, hub, endpoint, webPubSubAuthPolicy, serviceVersion);
}
if (credential == null) {
logger.logThrowableAsError(
new IllegalStateException("No credential has been specified - it must be non-null and non-empty."));
}
final Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration;
final String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
final String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId =
clientOptions == null ? httpLogOptions.getApplicationId() : clientOptions.getApplicationId();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion,
buildConfiguration));
policies.add(new CookiePolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy);
policies.add(webPubSubAuthPolicy);
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));
innerBuilder.pipeline(new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build());
return buildAsyncClient(innerBuilder, hub, endpoint, webPubSubAuthPolicy, serviceVersion);
} | this.endpoint = this.endpoint + ":" + port; | public WebPubSubAsyncServiceClient buildAsyncClient() {
if (hub == null || hub.isEmpty()) {
logger.logThrowableAsError(
new IllegalStateException("hub is not valid - it must be non-null and non-empty."));
}
if (endpoint == null && credential == null) {
final Map<String, String> csParams = parseConnectionString(connectionString);
if (!csParams.containsKey("endpoint") && !csParams.containsKey("accesskey")) {
logger.logThrowableAsError(new IllegalArgumentException(
"Connection string does not contain required 'endpoint' and 'accesskey' values"));
}
final String accessKey = csParams.get("accesskey");
this.credential = new AzureKeyCredential(accessKey);
String csEndpoint = csParams.get("endpoint");
URL url;
try {
url = new URL(csEndpoint);
this.endpoint = csEndpoint;
} catch (MalformedURLException e) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("Connection string contains invalid "
+ "endpoint", e));
}
String port = csParams.get("port");
if (!CoreUtils.isNullOrEmpty(port)) {
this.endpoint = UrlBuilder.parse(url).setPort(port).toString();
}
}
final AzureWebPubSubServiceRestAPIImplBuilder innerBuilder = new AzureWebPubSubServiceRestAPIImplBuilder();
if (endpoint == null || endpoint.isEmpty()) {
logger.logThrowableAsError(
new IllegalStateException("endpoint is not valid - it must be non-null and non-empty."));
}
innerBuilder.host(endpoint);
final WebPubSubServiceVersion serviceVersion =
version != null ? version : WebPubSubServiceVersion.getLatest();
WebPubSubAuthenticationPolicy webPubSubAuthPolicy = new WebPubSubAuthenticationPolicy(credential);
if (pipeline != null) {
innerBuilder.pipeline(pipeline);
return buildAsyncClient(innerBuilder, hub, endpoint, webPubSubAuthPolicy, serviceVersion);
}
if (credential == null) {
logger.logThrowableAsError(
new IllegalStateException("No credential has been specified - it must be non-null and non-empty."));
}
final Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration;
final String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
final String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId =
clientOptions == null ? httpLogOptions.getApplicationId() : clientOptions.getApplicationId();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion,
buildConfiguration));
policies.add(new CookiePolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy);
policies.add(webPubSubAuthPolicy);
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));
innerBuilder.pipeline(new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build());
return buildAsyncClient(innerBuilder, hub, endpoint, webPubSubAuthPolicy, serviceVersion);
} | class WebPubSubClientBuilder {
private final ClientLogger logger = new ClientLogger(WebPubSubClientBuilder.class);
private static final String WEBPUBSUB_PROPERTIES = "azure-messaging-webpubsub.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private static final HttpPipelinePolicy DEFAULT_RETRY_POLICY = new RetryPolicy();
private final Map<String, String> properties;
private final List<HttpPipelinePolicy> policies;
private String connectionString;
private String endpoint;
private AzureKeyCredential credential;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private RetryPolicy retryPolicy;
private Configuration configuration;
private WebPubSubServiceVersion version;
private String hub;
private ClientOptions clientOptions;
/**
* Creates a new builder instance with all values set to their default value.
*/
public WebPubSubClientBuilder() {
policies = new ArrayList<>();
httpLogOptions = new HttpLogOptions();
properties = CoreUtils.getProperties(WEBPUBSUB_PROPERTIES);
}
/**
* 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 WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};accesskey={accesskey_value}"
* @return The updated WebPubSubClientBuilder object.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public WebPubSubClientBuilder connectionString(final String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
this.connectionString = connectionString;
return this;
}
/**
* Sets the service endpoint for the Azure Web Pub Sub instance.
*
* @param endpoint The URL of the Azure Web Pub Sub instance to send service requests to, and receive responses
* from.
* @return The updated WebPubSubClientBuilder object.
* @throws IllegalArgumentException if {@code endpoint} is {@code null}.
*/
public WebPubSubClientBuilder endpoint(final String endpoint) {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link AzureKeyCredential} used to authenticate HTTP requests.
*
* @param credential AzureKeyCredential used to authenticate HTTP requests.
* @return The updated WebPubSubClientBuilder object.
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public WebPubSubClientBuilder credential(final AzureKeyCredential credential) {
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credential = credential;
return this;
}
/**
* Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or
* underscore.
*
* @param hub Target hub name, which should start with alphabetic characters and only contain alpha-numeric
* characters or underscore.
* @return The updated WebPubSubClientBuilder object.
* @throws NullPointerException If {@code hub} is {@code null}.
*/
public WebPubSubClientBuilder hub(final String hub) {
Objects.requireNonNull(hub, "'hub' cannot be null.");
this.hub = hub;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, default value of {@link com.azure.core.http.policy.HttpLogDetailLevel
* set.</p>
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder httpLogOptions(final HttpLogOptions logOptions) {
httpLogOptions = logOptions;
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 WebPubSubClientBuilder object.
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public WebPubSubClientBuilder addPolicy(final HttpPipelinePolicy policy) {
Objects.requireNonNull(policy);
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 WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder httpClient(final 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.
*
* If {@code pipeline} is set, all other settings are ignored, aside from
* {@link WebPubSubClientBuilder
* {@link WebPubSubServiceClient}.
*
* @param pipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder pipeline(final 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 WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder configuration(final Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used when each request is sent. The default retry policy will be
* used if not provided.
*
* @param retryPolicy user's retry policy applied to each request.
* @return The updated WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder retryPolicy(final RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link WebPubSubServiceVersion} 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 WebPubSubServiceVersion} of the service to be used when making requests.
* @return The updated WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder serviceVersion(final WebPubSubServiceVersion version) {
this.version = version;
return this;
}
/**
* Builds an instance of WebPubSubAsyncServiceClient with the provided parameters.
*
* @return an instance of WebPubSubAsyncServiceClient.
*/
private WebPubSubAsyncServiceClient buildAsyncClient(final AzureWebPubSubServiceRestAPIImplBuilder innerBuilder,
final String hub,
final String endpoint,
final WebPubSubAuthenticationPolicy webPubSubAuthPolicy,
final WebPubSubServiceVersion serviceVersion) {
return new WebPubSubAsyncServiceClient(
innerBuilder.buildClient().getWebPubSubs(), hub, endpoint, webPubSubAuthPolicy, serviceVersion);
}
/**
* Builds an instance of WebPubSubServiceClient with the provided parameters.
*
* @return an instance of WebPubSubServiceClient.
*/
public WebPubSubServiceClient buildClient() {
return new WebPubSubServiceClient(buildAsyncClient());
}
private Map<String, String> parseConnectionString(final String cs) {
final String[] params = cs.split(";");
final Map<String, String> connectionStringParams = new HashMap<>();
for (final String param : params) {
final String[] paramSplit = param.split("=", 2);
if (paramSplit.length != 2) {
continue;
}
final String key = paramSplit[0].trim().toLowerCase(Locale.ROOT);
if (connectionStringParams.containsKey(key)) {
logger.logThrowableAsError(new IllegalArgumentException(
"Duplicate connection string key parameter provided for key '" + key + "'"));
}
final String value = paramSplit[1].trim();
connectionStringParams.put(key, value);
}
return connectionStringParams;
}
} | class WebPubSubClientBuilder {
private final ClientLogger logger = new ClientLogger(WebPubSubClientBuilder.class);
private static final String WEBPUBSUB_PROPERTIES = "azure-messaging-webpubsub.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private static final HttpPipelinePolicy DEFAULT_RETRY_POLICY = new RetryPolicy();
private final Map<String, String> properties;
private final List<HttpPipelinePolicy> policies;
private String connectionString;
private String endpoint;
private AzureKeyCredential credential;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private RetryPolicy retryPolicy;
private Configuration configuration;
private WebPubSubServiceVersion version;
private String hub;
private ClientOptions clientOptions;
/**
* Creates a new builder instance with all values set to their default value.
*/
public WebPubSubClientBuilder() {
policies = new ArrayList<>();
httpLogOptions = new HttpLogOptions();
properties = CoreUtils.getProperties(WEBPUBSUB_PROPERTIES);
}
/**
* 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 WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};accesskey={accesskey_value}"
* @return The updated WebPubSubClientBuilder object.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public WebPubSubClientBuilder connectionString(final String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
this.connectionString = connectionString;
return this;
}
/**
* Sets the service endpoint for the Azure Web Pub Sub instance.
*
* @param endpoint The URL of the Azure Web Pub Sub instance to send service requests to, and receive responses
* from.
* @return The updated WebPubSubClientBuilder object.
* @throws IllegalArgumentException if {@code endpoint} is {@code null}.
*/
public WebPubSubClientBuilder endpoint(final String endpoint) {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
try {
new URL(endpoint);
} catch (MalformedURLException e) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be valid URL", e));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link AzureKeyCredential} used to authenticate HTTP requests.
*
* @param credential AzureKeyCredential used to authenticate HTTP requests.
* @return The updated WebPubSubClientBuilder object.
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public WebPubSubClientBuilder credential(final AzureKeyCredential credential) {
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credential = credential;
return this;
}
/**
* Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or
* underscore.
*
* @param hub Target hub name, which should start with alphabetic characters and only contain alpha-numeric
* characters or underscore.
* @return The updated WebPubSubClientBuilder object.
* @throws NullPointerException If {@code hub} is {@code null}.
*/
public WebPubSubClientBuilder hub(final String hub) {
Objects.requireNonNull(hub, "'hub' cannot be null.");
this.hub = hub;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, default value of {@link com.azure.core.http.policy.HttpLogDetailLevel
* set.</p>
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder httpLogOptions(final HttpLogOptions logOptions) {
httpLogOptions = logOptions;
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 WebPubSubClientBuilder object.
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public WebPubSubClientBuilder addPolicy(final HttpPipelinePolicy policy) {
Objects.requireNonNull(policy);
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 WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder httpClient(final 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.
*
* If {@code pipeline} is set, all other settings are ignored, aside from
* {@link WebPubSubClientBuilder
* {@link WebPubSubServiceClient}.
*
* @param pipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder pipeline(final 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 WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder configuration(final Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used when each request is sent. The default retry policy will be
* used if not provided.
*
* @param retryPolicy user's retry policy applied to each request.
* @return The updated WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder retryPolicy(final RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link WebPubSubServiceVersion} 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 WebPubSubServiceVersion} of the service to be used when making requests.
* @return The updated WebPubSubClientBuilder object.
*/
public WebPubSubClientBuilder serviceVersion(final WebPubSubServiceVersion version) {
this.version = version;
return this;
}
/**
* Builds an instance of WebPubSubAsyncServiceClient with the provided parameters.
*
* @return an instance of WebPubSubAsyncServiceClient.
*/
private WebPubSubAsyncServiceClient buildAsyncClient(final AzureWebPubSubServiceRestAPIImplBuilder innerBuilder,
final String hub,
final String endpoint,
final WebPubSubAuthenticationPolicy webPubSubAuthPolicy,
final WebPubSubServiceVersion serviceVersion) {
return new WebPubSubAsyncServiceClient(
innerBuilder.buildClient().getWebPubSubs(), hub, endpoint, webPubSubAuthPolicy, serviceVersion);
}
/**
* Builds an instance of WebPubSubServiceClient with the provided parameters.
*
* @return an instance of WebPubSubServiceClient.
*/
public WebPubSubServiceClient buildClient() {
return new WebPubSubServiceClient(buildAsyncClient());
}
private Map<String, String> parseConnectionString(final String cs) {
final String[] params = cs.split(";");
final Map<String, String> connectionStringParams = new HashMap<>();
for (final String param : params) {
final String[] paramSplit = param.split("=", 2);
if (paramSplit.length != 2) {
continue;
}
final String key = paramSplit[0].trim().toLowerCase(Locale.ROOT);
if (connectionStringParams.containsKey(key)) {
logger.logThrowableAsError(new IllegalArgumentException(
"Duplicate connection string key parameter provided for key '" + key + "'"));
}
final String value = paramSplit[1].trim();
connectionStringParams.put(key, value);
}
return connectionStringParams;
}
} |
Don't you have to delete the setting here? | public Mono<Void> globalCleanupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.deleteConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
} | new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE))); | public Mono<Void> globalCleanupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.deleteConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
} | class ListConfigurationSettingsTest extends ServiceTest<PerfStressOptions> {
private static final String KEY_PREFIX = "keyPrefix";
private static final String SETTING_VALUE = "value";
private static int settingCount = 1;
private static SettingSelector keyFilterSelector = new SettingSelector().setKeyFilter(KEY_PREFIX + "*");
/**
* The ListConfigurationSettingsTest class.
*
* @param options the configurable options for perf testing this class
*/
public ListConfigurationSettingsTest(PerfStressOptions options) {
super(options);
settingCount = options.getCount();
}
@Override
public Mono<Void> globalSetupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.setConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
}
@Override
@Override
public void run() {
configurationClient.listConfigurationSettings(keyFilterSelector);
}
@Override
public Mono<Void> runAsync() {
return configurationAsyncClient.listConfigurationSettings(keyFilterSelector).then();
}
} | class ListConfigurationSettingsTest extends ServiceTest<PerfStressOptions> {
private static final String KEY_PREFIX = "keyPrefix";
private static final String SETTING_VALUE = "value";
private static SettingSelector keyFilterSelector = new SettingSelector().setKeyFilter(KEY_PREFIX + "*");
private int settingCount = options.getCount();
/**
* The ListConfigurationSettingsTest class.
*
* @param options the configurable options for perf testing this class
*/
public ListConfigurationSettingsTest(PerfStressOptions options) {
super(options);
}
@Override
public Mono<Void> globalSetupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.setConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
}
@Override
@Override
public void run() {
configurationClient.listConfigurationSettings(keyFilterSelector);
}
@Override
public Mono<Void> runAsync() {
return configurationAsyncClient.listConfigurationSettings(keyFilterSelector).then();
}
} |
deleteConfigurationSetting() deletes the setting in the resource | public Mono<Void> globalCleanupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.deleteConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
} | new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE))); | public Mono<Void> globalCleanupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.deleteConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
} | class ListConfigurationSettingsTest extends ServiceTest<PerfStressOptions> {
private static final String KEY_PREFIX = "keyPrefix";
private static final String SETTING_VALUE = "value";
private static int settingCount = 1;
private static SettingSelector keyFilterSelector = new SettingSelector().setKeyFilter(KEY_PREFIX + "*");
/**
* The ListConfigurationSettingsTest class.
*
* @param options the configurable options for perf testing this class
*/
public ListConfigurationSettingsTest(PerfStressOptions options) {
super(options);
settingCount = options.getCount();
}
@Override
public Mono<Void> globalSetupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.setConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
}
@Override
@Override
public void run() {
configurationClient.listConfigurationSettings(keyFilterSelector);
}
@Override
public Mono<Void> runAsync() {
return configurationAsyncClient.listConfigurationSettings(keyFilterSelector).then();
}
} | class ListConfigurationSettingsTest extends ServiceTest<PerfStressOptions> {
private static final String KEY_PREFIX = "keyPrefix";
private static final String SETTING_VALUE = "value";
private static SettingSelector keyFilterSelector = new SettingSelector().setKeyFilter(KEY_PREFIX + "*");
private int settingCount = options.getCount();
/**
* The ListConfigurationSettingsTest class.
*
* @param options the configurable options for perf testing this class
*/
public ListConfigurationSettingsTest(PerfStressOptions options) {
super(options);
}
@Override
public Mono<Void> globalSetupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.setConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
}
@Override
@Override
public void run() {
configurationClient.listConfigurationSettings(keyFilterSelector);
}
@Override
public Mono<Void> runAsync() {
return configurationAsyncClient.listConfigurationSettings(keyFilterSelector).then();
}
} |
Missed it, sorry. | public Mono<Void> globalCleanupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.deleteConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
} | new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE))); | public Mono<Void> globalCleanupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.deleteConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
} | class ListConfigurationSettingsTest extends ServiceTest<PerfStressOptions> {
private static final String KEY_PREFIX = "keyPrefix";
private static final String SETTING_VALUE = "value";
private static int settingCount = 1;
private static SettingSelector keyFilterSelector = new SettingSelector().setKeyFilter(KEY_PREFIX + "*");
/**
* The ListConfigurationSettingsTest class.
*
* @param options the configurable options for perf testing this class
*/
public ListConfigurationSettingsTest(PerfStressOptions options) {
super(options);
settingCount = options.getCount();
}
@Override
public Mono<Void> globalSetupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.setConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
}
@Override
@Override
public void run() {
configurationClient.listConfigurationSettings(keyFilterSelector);
}
@Override
public Mono<Void> runAsync() {
return configurationAsyncClient.listConfigurationSettings(keyFilterSelector).then();
}
} | class ListConfigurationSettingsTest extends ServiceTest<PerfStressOptions> {
private static final String KEY_PREFIX = "keyPrefix";
private static final String SETTING_VALUE = "value";
private static SettingSelector keyFilterSelector = new SettingSelector().setKeyFilter(KEY_PREFIX + "*");
private int settingCount = options.getCount();
/**
* The ListConfigurationSettingsTest class.
*
* @param options the configurable options for perf testing this class
*/
public ListConfigurationSettingsTest(PerfStressOptions options) {
super(options);
}
@Override
public Mono<Void> globalSetupAsync() {
List<Mono<ConfigurationSetting>> settingMonoList = new ArrayList<>();
for (int i = 0; i < settingCount; i++) {
settingMonoList.add(configurationAsyncClient.setConfigurationSetting(
new ConfigurationSetting().setKey(KEY_PREFIX + i).setValue(SETTING_VALUE)));
}
return Flux.concat(settingMonoList).then();
}
@Override
@Override
public void run() {
configurationClient.listConfigurationSettings(keyFilterSelector);
}
@Override
public Mono<Void> runAsync() {
return configurationAsyncClient.listConfigurationSettings(keyFilterSelector).then();
}
} |
nit: is that better to have a static LOGGER? I know it is only used once but just want to discuss it. | public static String readSynonymsFromFile(Path filePath) {
try {
return new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new ClientLogger(Utility.class).logExceptionAsError(new UncheckedIOException(ex));
}
} | throw new ClientLogger(Utility.class).logExceptionAsError(new UncheckedIOException(ex)); | public static String readSynonymsFromFile(Path filePath) {
try {
return new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new ClientLogger(Utility.class).logExceptionAsError(new UncheckedIOException(ex));
}
} | class Utility {
public static final TypeReference<Map<String, Object>> MAP_STRING_OBJECT_TYPE_REFERENCE =
new TypeReference<Map<String, Object>>() { };
private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions();
private static final HttpLogOptions DEFAULT_LOG_OPTIONS = Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get();
private static final HttpHeaders HTTP_HEADERS = new HttpHeaders().set("return-client-request-id", "true");
private static final DecimalFormat COORDINATE_FORMATTER = new DecimalFormat();
private static final JacksonAdapter DEFAULT_SERIALIZER_ADAPTER;
/*
* Representation of the Multi-Status HTTP response code.
*/
private static final int MULTI_STATUS_CODE = 207;
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-search-documents.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
JacksonAdapter adapter = new JacksonAdapter();
UntypedObjectDeserializer defaultDeserializer = new UntypedObjectDeserializer(null, null);
Iso8601DateDeserializer iso8601DateDeserializer = new Iso8601DateDeserializer(defaultDeserializer);
SimpleModule module = new SimpleModule();
module.addDeserializer(Object.class, iso8601DateDeserializer);
adapter.serializer()
.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
.registerModule(Iso8601DateSerializer.getModule())
.registerModule(module);
DEFAULT_SERIALIZER_ADAPTER = adapter;
}
public static JacksonAdapter getDefaultSerializerAdapter() {
return DEFAULT_SERIALIZER_ADAPTER;
}
public static <T> T convertValue(Object initialValue, Class<T> newValueType) throws IOException {
return DEFAULT_SERIALIZER_ADAPTER.serializer().convertValue(initialValue, newValueType);
}
public static HttpPipeline buildHttpPipeline(ClientOptions clientOptions, HttpLogOptions logOptions,
Configuration configuration, RetryPolicy retryPolicy, AzureKeyCredential credential,
List<HttpPipelinePolicy> perCallPolicies, List<HttpPipelinePolicy> perRetryPolicies, HttpClient httpClient) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
ClientOptions buildClientOptions = (clientOptions == null) ? DEFAULT_CLIENT_OPTIONS : clientOptions;
HttpLogOptions buildLogOptions = (logOptions == null) ? DEFAULT_LOG_OPTIONS : logOptions;
String applicationId = CoreUtils.getApplicationId(buildClientOptions, buildLogOptions);
final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>();
httpPipelinePolicies.add(new AddHeadersPolicy(HTTP_HEADERS));
httpPipelinePolicies.add(new AddHeadersFromContextPolicy());
httpPipelinePolicies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
httpPipelinePolicies.add(new RequestIdPolicy());
httpPipelinePolicies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies);
httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
httpPipelinePolicies.add(new AddDatePolicy());
httpPipelinePolicies.add(new AzureKeyCredentialPolicy("api-key", credential));
httpPipelinePolicies.addAll(perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies);
HttpHeaders headers = new HttpHeaders();
buildClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue()));
if (headers.getSize() > 0) {
httpPipelinePolicies.add(new AddHeadersPolicy(headers));
}
httpPipelinePolicies.add(new HttpLoggingPolicy(buildLogOptions));
return new HttpPipelineBuilder()
.clientOptions(buildClientOptions)
.httpClient(httpClient)
.policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0]))
.build();
}
public static Mono<Response<IndexDocumentsResult>> indexDocumentsWithResponse(SearchIndexClientImpl restClient,
List<com.azure.search.documents.implementation.models.IndexAction> actions, boolean throwOnAnyError,
Context context, ClientLogger logger) {
try {
return restClient.getDocuments().indexWithResponseAsync(new IndexBatch(actions), null, context)
.onErrorMap(MappingUtils::exceptionMapper)
.flatMap(response -> (response.getStatusCode() == MULTI_STATUS_CODE && throwOnAnyError)
? Mono.error(new IndexBatchException(IndexDocumentsResultConverter.map(response.getValue())))
: Mono.just(response).map(MappingUtils::mappingIndexDocumentResultResponse));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
public static SearchIndexClientImpl buildRestClient(String endpoint, String indexName, HttpPipeline httpPipeline,
SerializerAdapter adapter) {
return new SearchIndexClientImplBuilder()
.endpoint(endpoint)
.indexName(indexName)
.pipeline(httpPipeline)
.serializerAdapter(adapter)
.buildClient();
}
public static synchronized String formatCoordinate(double coordinate) {
return COORDINATE_FORMATTER.format(coordinate);
}
private Utility() {
}
} | class Utility {
public static final TypeReference<Map<String, Object>> MAP_STRING_OBJECT_TYPE_REFERENCE =
new TypeReference<Map<String, Object>>() { };
private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions();
private static final HttpLogOptions DEFAULT_LOG_OPTIONS = Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get();
private static final HttpHeaders HTTP_HEADERS = new HttpHeaders().set("return-client-request-id", "true");
private static final DecimalFormat COORDINATE_FORMATTER = new DecimalFormat();
private static final JacksonAdapter DEFAULT_SERIALIZER_ADAPTER;
/*
* Representation of the Multi-Status HTTP response code.
*/
private static final int MULTI_STATUS_CODE = 207;
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-search-documents.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
JacksonAdapter adapter = new JacksonAdapter();
UntypedObjectDeserializer defaultDeserializer = new UntypedObjectDeserializer(null, null);
Iso8601DateDeserializer iso8601DateDeserializer = new Iso8601DateDeserializer(defaultDeserializer);
SimpleModule module = new SimpleModule();
module.addDeserializer(Object.class, iso8601DateDeserializer);
adapter.serializer()
.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
.registerModule(Iso8601DateSerializer.getModule())
.registerModule(module);
DEFAULT_SERIALIZER_ADAPTER = adapter;
}
public static JacksonAdapter getDefaultSerializerAdapter() {
return DEFAULT_SERIALIZER_ADAPTER;
}
public static <T> T convertValue(Object initialValue, Class<T> newValueType) throws IOException {
return DEFAULT_SERIALIZER_ADAPTER.serializer().convertValue(initialValue, newValueType);
}
public static HttpPipeline buildHttpPipeline(ClientOptions clientOptions, HttpLogOptions logOptions,
Configuration configuration, RetryPolicy retryPolicy, AzureKeyCredential credential,
List<HttpPipelinePolicy> perCallPolicies, List<HttpPipelinePolicy> perRetryPolicies, HttpClient httpClient) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
ClientOptions buildClientOptions = (clientOptions == null) ? DEFAULT_CLIENT_OPTIONS : clientOptions;
HttpLogOptions buildLogOptions = (logOptions == null) ? DEFAULT_LOG_OPTIONS : logOptions;
String applicationId = CoreUtils.getApplicationId(buildClientOptions, buildLogOptions);
final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>();
httpPipelinePolicies.add(new AddHeadersPolicy(HTTP_HEADERS));
httpPipelinePolicies.add(new AddHeadersFromContextPolicy());
httpPipelinePolicies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
httpPipelinePolicies.add(new RequestIdPolicy());
httpPipelinePolicies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies);
httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
httpPipelinePolicies.add(new AddDatePolicy());
httpPipelinePolicies.add(new AzureKeyCredentialPolicy("api-key", credential));
httpPipelinePolicies.addAll(perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies);
HttpHeaders headers = new HttpHeaders();
buildClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue()));
if (headers.getSize() > 0) {
httpPipelinePolicies.add(new AddHeadersPolicy(headers));
}
httpPipelinePolicies.add(new HttpLoggingPolicy(buildLogOptions));
return new HttpPipelineBuilder()
.clientOptions(buildClientOptions)
.httpClient(httpClient)
.policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0]))
.build();
}
public static Mono<Response<IndexDocumentsResult>> indexDocumentsWithResponse(SearchIndexClientImpl restClient,
List<com.azure.search.documents.implementation.models.IndexAction> actions, boolean throwOnAnyError,
Context context, ClientLogger logger) {
try {
return restClient.getDocuments().indexWithResponseAsync(new IndexBatch(actions), null, context)
.onErrorMap(MappingUtils::exceptionMapper)
.flatMap(response -> (response.getStatusCode() == MULTI_STATUS_CODE && throwOnAnyError)
? Mono.error(new IndexBatchException(IndexDocumentsResultConverter.map(response.getValue())))
: Mono.just(response).map(MappingUtils::mappingIndexDocumentResultResponse));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
public static SearchIndexClientImpl buildRestClient(String endpoint, String indexName, HttpPipeline httpPipeline,
SerializerAdapter adapter) {
return new SearchIndexClientImplBuilder()
.endpoint(endpoint)
.indexName(indexName)
.pipeline(httpPipeline)
.serializerAdapter(adapter)
.buildClient();
}
public static synchronized String formatCoordinate(double coordinate) {
return COORDINATE_FORMATTER.format(coordinate);
}
private Utility() {
}
} |
nit: Should we make the error message a variable in the Checkstyle instead of performing a format on every error. | public void visitToken(DetailAST token) {
switch (token.getType()) {
case TokenTypes.CLASS_DEF:
case TokenTypes.METHOD_DEF:
case TokenTypes.VARIABLE_DEF:
if (!isPublicApi(token)) {
break;
}
final String tokenName = token.findFirstToken(TokenTypes.IDENT).getText();
if (!hasBlacklistedWords(tokenName)) {
break;
}
if (token.getType() == TokenTypes.VARIABLE_DEF && ScopeUtil.isInInterfaceBlock(token)) {
break;
}
log(token, String.format(ERROR_MESSAGE, tokenName, String.join(", ", this.blacklistedWords)));
break;
default:
break;
}
} | log(token, String.format(ERROR_MESSAGE, tokenName, String.join(", ", this.blacklistedWords))); | public void visitToken(DetailAST token) {
switch (token.getType()) {
case TokenTypes.CLASS_DEF:
case TokenTypes.METHOD_DEF:
case TokenTypes.VARIABLE_DEF:
if (!isPublicApi(token)) {
break;
}
final String tokenName = token.findFirstToken(TokenTypes.IDENT).getText();
if (!hasBlacklistedWords(tokenName)) {
break;
}
if (token.getType() == TokenTypes.VARIABLE_DEF && ScopeUtil.isInInterfaceBlock(token)) {
break;
}
log(token, String.format(ERROR_MESSAGE, tokenName, String.join(", ", this.blacklistedWords)));
break;
default:
break;
}
} | class BlacklistedWordsCheck extends AbstractCheck {
private final Set<String> blacklistedWords = new HashSet<>();
private static final String ERROR_MESSAGE = "%s, All Public API Classes, Fields and Methods should follow "
+ "Camelcase standards for the following words: %s.";
/**
* Adds words that Classes, Methods and Variables that should follow Camelcasing standards
* @param blacklistedWords words that should follow normal Camelcasing standards
*/
public final void setBlacklistedWords(String... blacklistedWords) {
if (blacklistedWords != null) {
Collections.addAll(this.blacklistedWords, blacklistedWords);
}
}
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {TokenTypes.CLASS_DEF,
TokenTypes.METHOD_DEF,
TokenTypes.VARIABLE_DEF};
}
@Override
/**
* Should we check member with given modifiers.
*
* @param token modifiers of member to check.
* @return true if we should check such member.
*/
private boolean isPublicApi(DetailAST token) {
final DetailAST modifiersAST = token.findFirstToken(TokenTypes.MODIFIERS);
final AccessModifierOption accessModifier = CheckUtil.getAccessModifierFromModifiersToken(token);
final boolean isStatic = modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
return (accessModifier.equals(AccessModifierOption.PUBLIC) || accessModifier.equals(AccessModifierOption.PROTECTED)) && !isStatic;
}
/**
* Gets the disallowed abbreviation contained in given String.
* @param tokenName the given String.
* @return the disallowed abbreviation contained in given String as a
* separate String.
*/
private boolean hasBlacklistedWords(String tokenName) {
for (String blacklistedWord : blacklistedWords) {
if (tokenName.contains(blacklistedWord)) {
return true;
}
}
return false;
}
} | class BlacklistedWordsCheck extends AbstractCheck {
private final Set<String> blacklistedWords = new HashSet<>();
private static final String ERROR_MESSAGE = "%s, All Public API Classes, Fields and Methods should follow "
+ "Camelcase standards for the following words: %s.";
/**
* Adds words that Classes, Methods and Variables that should follow Camelcasing standards
* @param blacklistedWords words that should follow normal Camelcasing standards
*/
public final void setBlacklistedWords(String... blacklistedWords) {
if (blacklistedWords != null) {
Collections.addAll(this.blacklistedWords, blacklistedWords);
}
}
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {TokenTypes.CLASS_DEF,
TokenTypes.METHOD_DEF,
TokenTypes.VARIABLE_DEF};
}
@Override
/**
* Should we check member with given modifiers.
*
* @param token modifiers of member to check.
* @return true if we should check such member.
*/
private boolean isPublicApi(DetailAST token) {
final DetailAST modifiersAST = token.findFirstToken(TokenTypes.MODIFIERS);
final AccessModifierOption accessModifier = CheckUtil.getAccessModifierFromModifiersToken(token);
final boolean isStatic = modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
return (accessModifier.equals(AccessModifierOption.PUBLIC) || accessModifier.equals(AccessModifierOption.PROTECTED)) && !isStatic;
}
/**
* Gets the disallowed abbreviation contained in given String.
* @param tokenName the given String.
* @return the disallowed abbreviation contained in given String as a
* separate String.
*/
private boolean hasBlacklistedWords(String tokenName) {
for (String blacklistedWord : blacklistedWords) {
if (tokenName.contains(blacklistedWord)) {
return true;
}
}
return false;
}
} |
If only 4 messages are added to the `sink`, why is `take(count)` necessary? | void newLinkOnClose() {
final int count = 4;
final Message message3 = mock(Message.class);
final Message message4 = mock(Message.class);
final TestPublisher<AmqpEndpointState> connection2EndpointProcessor = TestPublisher.create();
when(link2.getEndpointStates()).thenReturn(connection2EndpointProcessor.flux());
when(link2.receive()).thenReturn(Flux.create(sink -> sink.next(message2)));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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(link3.addCredits(anyInt())).thenReturn(Mono.empty());
when(link1.getCredits()).thenReturn(1);
when(link2.getCredits()).thenReturn(1);
when(link3.getCredits()).thenReturn(1);
when(link1.closeAsync()).thenReturn(Mono.empty());
when(link2.closeAsync()).thenReturn(Mono.empty());
when(link3.closeAsync()).thenReturn(Mono.empty());
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
StepVerifier.create(processor.take(count))
.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());
} | StepVerifier.create(processor.take(count)) | void newLinkOnClose() {
final int count = 4;
final Message message3 = mock(Message.class);
final Message message4 = mock(Message.class);
final TestPublisher<AmqpEndpointState> connection2EndpointProcessor = TestPublisher.create();
when(link2.getEndpointStates()).thenReturn(connection2EndpointProcessor.flux());
when(link2.receive()).thenReturn(Flux.create(sink -> sink.next(message2)));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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(link3.addCredits(anyInt())).thenReturn(Mono.empty());
when(link1.getCredits()).thenReturn(1);
when(link2.getCredits()).thenReturn(1);
when(link3.getCredits()).thenReturn(1);
when(link1.closeAsync()).thenReturn(Mono.empty());
when(link2.closeAsync()).thenReturn(Mono.empty());
when(link3.closeAsync()).thenReturn(Mono.empty());
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
StepVerifier.create(processor.take(count))
.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());
} | 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());
when(link1.addCredits(anyInt())).thenReturn(Mono.empty());
}
@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
void createNewLink() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(2);
when(link1.getCredits()).thenReturn(1);
when(link1.addCredits(eq(PREFETCH - 1))).thenAnswer(invocation -> {
countDownLatch.countDown();
return Mono.empty();
});
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
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);
}
/**
* 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
/**
* 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));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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(() -> {
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(link2.addCredits(anyInt())).thenReturn(Mono.empty());
when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link3.receive()).thenReturn(Flux.never());
when(link3.addCredits(anyInt())).thenReturn(Mono.empty());
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.createCold();
final ServiceBusReceiveLinkProcessor processor = linkGenerator.flux().subscribeWith(linkProcessor);
final TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.createCold();
final TestPublisher<Message> messages = TestPublisher.createCold();
when(link1.getEndpointStates()).thenReturn(endpointStates.flux());
when(link1.receive()).thenReturn(messages.flux());
final TestPublisher<AmqpEndpointState> endpointStates2 = TestPublisher.createCold();
when(link2.getEndpointStates()).thenReturn(endpointStates2.flux());
when(link2.receive()).thenReturn(Flux.never());
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> {
linkGenerator.next(link1);
endpointStates.next(AmqpEndpointState.ACTIVE);
})
.then(() -> {
linkGenerator.complete();
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() throws InterruptedException {
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
final Duration shortWait = Duration.ofSeconds(5);
when(link1.getCredits()).thenReturn(0);
when(link1.closeAsync()).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> {
endpointProcessor.next(AmqpEndpointState.ACTIVE);
messagePublisher.next(message1);
})
.expectNext(message1)
.then(() -> messagePublisher.next(message2))
.expectNext(message2)
.then(() -> endpointProcessor.complete())
.expectComplete()
.verify(shortWait);
TimeUnit.SECONDS.sleep(shortWait.getSeconds());
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);
when(link1.getCredits()).thenReturn(0);
when(link1.addCredits(eq(PREFETCH))).thenAnswer(invocation -> {
countDownLatch.countDown();
return Mono.empty();
});
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
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));
}
} | 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());
when(link1.addCredits(anyInt())).thenReturn(Mono.empty());
}
@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
void createNewLink() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(2);
when(link1.getCredits()).thenReturn(1);
when(link1.addCredits(eq(PREFETCH - 1))).thenAnswer(invocation -> {
countDownLatch.countDown();
return Mono.empty();
});
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
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);
}
/**
* 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
/**
* 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));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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(() -> {
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(link2.addCredits(anyInt())).thenReturn(Mono.empty());
when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link3.receive()).thenReturn(Flux.never());
when(link3.addCredits(anyInt())).thenReturn(Mono.empty());
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.createCold();
final ServiceBusReceiveLinkProcessor processor = linkGenerator.flux().subscribeWith(linkProcessor);
final TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.createCold();
final TestPublisher<Message> messages = TestPublisher.createCold();
when(link1.getEndpointStates()).thenReturn(endpointStates.flux());
when(link1.receive()).thenReturn(messages.flux());
final TestPublisher<AmqpEndpointState> endpointStates2 = TestPublisher.createCold();
when(link2.getEndpointStates()).thenReturn(endpointStates2.flux());
when(link2.receive()).thenReturn(Flux.never());
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> {
linkGenerator.next(link1);
endpointStates.next(AmqpEndpointState.ACTIVE);
})
.then(() -> {
linkGenerator.complete();
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() throws InterruptedException {
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
final Duration shortWait = Duration.ofSeconds(5);
when(link1.getCredits()).thenReturn(0);
when(link1.closeAsync()).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> {
endpointProcessor.next(AmqpEndpointState.ACTIVE);
messagePublisher.next(message1);
})
.expectNext(message1)
.then(() -> messagePublisher.next(message2))
.expectNext(message2)
.then(() -> endpointProcessor.complete())
.expectComplete()
.verify(shortWait);
TimeUnit.SECONDS.sleep(shortWait.getSeconds());
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);
when(link1.getCredits()).thenReturn(0);
when(link1.addCredits(eq(PREFETCH))).thenAnswer(invocation -> {
countDownLatch.countDown();
return Mono.empty();
});
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
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));
}
} |
It specifically complete the reactor stream after count instead of "ask for next and not receiving and completing". | void newLinkOnClose() {
final int count = 4;
final Message message3 = mock(Message.class);
final Message message4 = mock(Message.class);
final TestPublisher<AmqpEndpointState> connection2EndpointProcessor = TestPublisher.create();
when(link2.getEndpointStates()).thenReturn(connection2EndpointProcessor.flux());
when(link2.receive()).thenReturn(Flux.create(sink -> sink.next(message2)));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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(link3.addCredits(anyInt())).thenReturn(Mono.empty());
when(link1.getCredits()).thenReturn(1);
when(link2.getCredits()).thenReturn(1);
when(link3.getCredits()).thenReturn(1);
when(link1.closeAsync()).thenReturn(Mono.empty());
when(link2.closeAsync()).thenReturn(Mono.empty());
when(link3.closeAsync()).thenReturn(Mono.empty());
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
StepVerifier.create(processor.take(count))
.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());
} | StepVerifier.create(processor.take(count)) | void newLinkOnClose() {
final int count = 4;
final Message message3 = mock(Message.class);
final Message message4 = mock(Message.class);
final TestPublisher<AmqpEndpointState> connection2EndpointProcessor = TestPublisher.create();
when(link2.getEndpointStates()).thenReturn(connection2EndpointProcessor.flux());
when(link2.receive()).thenReturn(Flux.create(sink -> sink.next(message2)));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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(link3.addCredits(anyInt())).thenReturn(Mono.empty());
when(link1.getCredits()).thenReturn(1);
when(link2.getCredits()).thenReturn(1);
when(link3.getCredits()).thenReturn(1);
when(link1.closeAsync()).thenReturn(Mono.empty());
when(link2.closeAsync()).thenReturn(Mono.empty());
when(link3.closeAsync()).thenReturn(Mono.empty());
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
StepVerifier.create(processor.take(count))
.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());
} | 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());
when(link1.addCredits(anyInt())).thenReturn(Mono.empty());
}
@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
void createNewLink() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(2);
when(link1.getCredits()).thenReturn(1);
when(link1.addCredits(eq(PREFETCH - 1))).thenAnswer(invocation -> {
countDownLatch.countDown();
return Mono.empty();
});
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
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);
}
/**
* 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
/**
* 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));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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(() -> {
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(link2.addCredits(anyInt())).thenReturn(Mono.empty());
when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link3.receive()).thenReturn(Flux.never());
when(link3.addCredits(anyInt())).thenReturn(Mono.empty());
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.createCold();
final ServiceBusReceiveLinkProcessor processor = linkGenerator.flux().subscribeWith(linkProcessor);
final TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.createCold();
final TestPublisher<Message> messages = TestPublisher.createCold();
when(link1.getEndpointStates()).thenReturn(endpointStates.flux());
when(link1.receive()).thenReturn(messages.flux());
final TestPublisher<AmqpEndpointState> endpointStates2 = TestPublisher.createCold();
when(link2.getEndpointStates()).thenReturn(endpointStates2.flux());
when(link2.receive()).thenReturn(Flux.never());
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> {
linkGenerator.next(link1);
endpointStates.next(AmqpEndpointState.ACTIVE);
})
.then(() -> {
linkGenerator.complete();
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() throws InterruptedException {
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
final Duration shortWait = Duration.ofSeconds(5);
when(link1.getCredits()).thenReturn(0);
when(link1.closeAsync()).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> {
endpointProcessor.next(AmqpEndpointState.ACTIVE);
messagePublisher.next(message1);
})
.expectNext(message1)
.then(() -> messagePublisher.next(message2))
.expectNext(message2)
.then(() -> endpointProcessor.complete())
.expectComplete()
.verify(shortWait);
TimeUnit.SECONDS.sleep(shortWait.getSeconds());
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);
when(link1.getCredits()).thenReturn(0);
when(link1.addCredits(eq(PREFETCH))).thenAnswer(invocation -> {
countDownLatch.countDown();
return Mono.empty();
});
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
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));
}
} | 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());
when(link1.addCredits(anyInt())).thenReturn(Mono.empty());
}
@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
void createNewLink() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(2);
when(link1.getCredits()).thenReturn(1);
when(link1.addCredits(eq(PREFETCH - 1))).thenAnswer(invocation -> {
countDownLatch.countDown();
return Mono.empty();
});
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
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);
}
/**
* 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
/**
* 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));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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));
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
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(() -> {
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(link2.addCredits(anyInt())).thenReturn(Mono.empty());
when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link3.receive()).thenReturn(Flux.never());
when(link3.addCredits(anyInt())).thenReturn(Mono.empty());
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.createCold();
final ServiceBusReceiveLinkProcessor processor = linkGenerator.flux().subscribeWith(linkProcessor);
final TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.createCold();
final TestPublisher<Message> messages = TestPublisher.createCold();
when(link1.getEndpointStates()).thenReturn(endpointStates.flux());
when(link1.receive()).thenReturn(messages.flux());
final TestPublisher<AmqpEndpointState> endpointStates2 = TestPublisher.createCold();
when(link2.getEndpointStates()).thenReturn(endpointStates2.flux());
when(link2.receive()).thenReturn(Flux.never());
when(link2.addCredits(anyInt())).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> {
linkGenerator.next(link1);
endpointStates.next(AmqpEndpointState.ACTIVE);
})
.then(() -> {
linkGenerator.complete();
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() throws InterruptedException {
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
final Duration shortWait = Duration.ofSeconds(5);
when(link1.getCredits()).thenReturn(0);
when(link1.closeAsync()).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> {
endpointProcessor.next(AmqpEndpointState.ACTIVE);
messagePublisher.next(message1);
})
.expectNext(message1)
.then(() -> messagePublisher.next(message2))
.expectNext(message2)
.then(() -> endpointProcessor.complete())
.expectComplete()
.verify(shortWait);
TimeUnit.SECONDS.sleep(shortWait.getSeconds());
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);
when(link1.getCredits()).thenReturn(0);
when(link1.addCredits(eq(PREFETCH))).thenAnswer(invocation -> {
countDownLatch.countDown();
return Mono.empty();
});
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
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));
}
} |
nit: consistent use of `this`. In the method above, you did not reference member variables with `this`. In general, unless there is a naming conflict, I would remove `this`. | public String getFullyQualifiedNamespace() {
return this.endpoint.getHost();
} | return this.endpoint.getHost(); | public String getFullyQualifiedNamespace() {
return endpoint.getHost();
} | class EventHubConnectionStringProperties {
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private final String sharedAccessSignature;
private EventHubConnectionStringProperties(ConnectionStringProperties properties) {
this.endpoint = properties.getEndpoint();
this.entityPath = properties.getEntityPath();
this.sharedAccessKeyName = properties.getSharedAccessKeyName();
this.sharedAccessKey = properties.getSharedAccessKey();
this.sharedAccessSignature = properties.getSharedAccessSignature();
}
/**
* Parse a Event Hub connection string into an instance of this class.
*
* @param connectionString The connection string to be parsed.
*
* @return An instance of this class.
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if the {@code connectionString} is empty or malformed.
*/
public static EventHubConnectionStringProperties parse(String connectionString) {
return new EventHubConnectionStringProperties(new ConnectionStringProperties(connectionString));
}
/**
* Gets the "EntityPath" value of the connection string.
*
* @return The entity path, or {@code null} if the connection string doesn't have an "EntityPath".
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the "Endpoint" value of the connection string.
*
* @return The endpoint.
*/
public String getEndpoint() {
return String.format("%s:
}
/**
* Gets the fully qualified namespace, or hostname, from the connection string "Endpoint" section.
*
* @return The fully qualified namespace.
*/
/**
* Gets the "SharedAccessKeyName" section of the connection string.
*
* @return The shared access key name, or {@code null} if the connection string doesn't have a
* "SharedAccessKeyName".
*/
public String getSharedAccessKeyName() {
return this.sharedAccessKeyName;
}
/**
* Gets the "SharedAccessSignature" section of the connection string.
*
* @return The shared access key value, or {@code null} if the connection string doesn't have a
* "SharedAccessSignature".
*/
public String getSharedAccessKey() {
return this.sharedAccessKey;
}
/**
* Gets the "SharedAccessSignature" section of the connection string.
*
* @return The shared access signature, or {@code null} if the connection string doesn't have a
* "SharedAccessSignature".
*/
public String getSharedAccessSignature() {
return this.sharedAccessSignature;
}
} | class EventHubConnectionStringProperties {
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private EventHubConnectionStringProperties(ConnectionStringProperties properties) {
this.endpoint = properties.getEndpoint();
this.entityPath = properties.getEntityPath();
this.sharedAccessKeyName = properties.getSharedAccessKeyName();
this.sharedAccessKey = properties.getSharedAccessKey();
}
/**
* Parse a Event Hub connection string into an instance of this class.
*
* @param connectionString The connection string to be parsed.
*
* @return An instance of this class.
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if the {@code connectionString} is empty or malformed.
*/
public static EventHubConnectionStringProperties parse(String connectionString) {
return new EventHubConnectionStringProperties(new ConnectionStringProperties(connectionString));
}
/**
* Gets the "EntityPath" value of the connection string.
*
* @return The entity path, or {@code null} if the connection string doesn't have an "EntityPath".
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the "Endpoint" value of the connection string.
*
* @return The endpoint.
*/
public String getEndpoint() {
return String.format("%s:
}
/**
* Gets the fully qualified namespace, or hostname, from the connection string "Endpoint" section.
*
* @return The fully qualified namespace.
*/
/**
* Gets the "SharedAccessKeyName" section of the connection string.
*
* @return The shared access key name, or {@code null} if the connection string doesn't have a
* "SharedAccessKeyName".
*/
public String getSharedAccessKeyName() {
return sharedAccessKeyName;
}
/**
* Gets the "SharedAccessSignature" section of the connection string.
*
* @return The shared access key value, or {@code null} if the connection string doesn't have a
* "SharedAccessSignature".
*/
public String getSharedAccessKey() {
return sharedAccessKey;
}
} |
According to your comment, fixed in new version. | public String getFullyQualifiedNamespace() {
return this.endpoint.getHost();
} | return this.endpoint.getHost(); | public String getFullyQualifiedNamespace() {
return endpoint.getHost();
} | class EventHubConnectionStringProperties {
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private final String sharedAccessSignature;
private EventHubConnectionStringProperties(ConnectionStringProperties properties) {
this.endpoint = properties.getEndpoint();
this.entityPath = properties.getEntityPath();
this.sharedAccessKeyName = properties.getSharedAccessKeyName();
this.sharedAccessKey = properties.getSharedAccessKey();
this.sharedAccessSignature = properties.getSharedAccessSignature();
}
/**
* Parse a Event Hub connection string into an instance of this class.
*
* @param connectionString The connection string to be parsed.
*
* @return An instance of this class.
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if the {@code connectionString} is empty or malformed.
*/
public static EventHubConnectionStringProperties parse(String connectionString) {
return new EventHubConnectionStringProperties(new ConnectionStringProperties(connectionString));
}
/**
* Gets the "EntityPath" value of the connection string.
*
* @return The entity path, or {@code null} if the connection string doesn't have an "EntityPath".
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the "Endpoint" value of the connection string.
*
* @return The endpoint.
*/
public String getEndpoint() {
return String.format("%s:
}
/**
* Gets the fully qualified namespace, or hostname, from the connection string "Endpoint" section.
*
* @return The fully qualified namespace.
*/
/**
* Gets the "SharedAccessKeyName" section of the connection string.
*
* @return The shared access key name, or {@code null} if the connection string doesn't have a
* "SharedAccessKeyName".
*/
public String getSharedAccessKeyName() {
return this.sharedAccessKeyName;
}
/**
* Gets the "SharedAccessSignature" section of the connection string.
*
* @return The shared access key value, or {@code null} if the connection string doesn't have a
* "SharedAccessSignature".
*/
public String getSharedAccessKey() {
return this.sharedAccessKey;
}
/**
* Gets the "SharedAccessSignature" section of the connection string.
*
* @return The shared access signature, or {@code null} if the connection string doesn't have a
* "SharedAccessSignature".
*/
public String getSharedAccessSignature() {
return this.sharedAccessSignature;
}
} | class EventHubConnectionStringProperties {
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private EventHubConnectionStringProperties(ConnectionStringProperties properties) {
this.endpoint = properties.getEndpoint();
this.entityPath = properties.getEntityPath();
this.sharedAccessKeyName = properties.getSharedAccessKeyName();
this.sharedAccessKey = properties.getSharedAccessKey();
}
/**
* Parse a Event Hub connection string into an instance of this class.
*
* @param connectionString The connection string to be parsed.
*
* @return An instance of this class.
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if the {@code connectionString} is empty or malformed.
*/
public static EventHubConnectionStringProperties parse(String connectionString) {
return new EventHubConnectionStringProperties(new ConnectionStringProperties(connectionString));
}
/**
* Gets the "EntityPath" value of the connection string.
*
* @return The entity path, or {@code null} if the connection string doesn't have an "EntityPath".
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the "Endpoint" value of the connection string.
*
* @return The endpoint.
*/
public String getEndpoint() {
return String.format("%s:
}
/**
* Gets the fully qualified namespace, or hostname, from the connection string "Endpoint" section.
*
* @return The fully qualified namespace.
*/
/**
* Gets the "SharedAccessKeyName" section of the connection string.
*
* @return The shared access key name, or {@code null} if the connection string doesn't have a
* "SharedAccessKeyName".
*/
public String getSharedAccessKeyName() {
return sharedAccessKeyName;
}
/**
* Gets the "SharedAccessSignature" section of the connection string.
*
* @return The shared access key value, or {@code null} if the connection string doesn't have a
* "SharedAccessSignature".
*/
public String getSharedAccessKey() {
return sharedAccessKey;
}
} |
Does base class method call need to be "synchronized"/single threaded as well? | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | synchronized(this) { | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} |
Does base class method call need to be "synchronized"/single threaded as well? | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.LEASE);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_ETAG,
this.eTag);
this.feedRange.setProperties(
this,
true);
}
} | synchronized(this) { | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.LEASE);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_ETAG,
this.eTag);
this.feedRange.setProperties(
this,
true);
}
} | class ChangeFeedStartFromETagAndFeedRangeImpl extends ChangeFeedStartFromInternal {
private final String eTag;
private final FeedRangeInternal feedRange;
public ChangeFeedStartFromETagAndFeedRangeImpl(String eTag, FeedRangeInternal feedRange) {
super();
checkNotNull(feedRange, "Argument 'feedRange' must not be null");
this.eTag = eTag;
this.feedRange = feedRange;
}
public String getETag() {
return this.eTag;
}
public FeedRangeInternal getFeedRange() {
return this.feedRange;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromETagAndFeedRangeImpl)) {
return false;
}
ChangeFeedStartFromETagAndFeedRangeImpl otherStartFrom =
(ChangeFeedStartFromETagAndFeedRangeImpl)obj;
if (this.eTag == null) {
return otherStartFrom.eTag == null &&
this.feedRange.equals(otherStartFrom.feedRange);
}
return this.eTag.compareTo(otherStartFrom.eTag) == 0 &&
this.feedRange.equals(otherStartFrom.feedRange);
}
@Override
public int hashCode() {
int hash = 1;
hash = (hash * 397) ^ this.feedRange.hashCode();
if (this.eTag != null) {
hash = (hash * 397) ^ this.eTag.hashCode();
}
return hash;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
if (this.eTag != null) {
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
this.eTag);
}
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
} | class ChangeFeedStartFromETagAndFeedRangeImpl extends ChangeFeedStartFromInternal {
private final String eTag;
private final FeedRangeInternal feedRange;
public ChangeFeedStartFromETagAndFeedRangeImpl(String eTag, FeedRangeInternal feedRange) {
super();
checkNotNull(feedRange, "Argument 'feedRange' must not be null");
this.eTag = eTag;
this.feedRange = feedRange;
}
public String getETag() {
return this.eTag;
}
public FeedRangeInternal getFeedRange() {
return this.feedRange;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromETagAndFeedRangeImpl)) {
return false;
}
ChangeFeedStartFromETagAndFeedRangeImpl otherStartFrom =
(ChangeFeedStartFromETagAndFeedRangeImpl)obj;
if (this.eTag == null) {
return otherStartFrom.eTag == null &&
this.feedRange.equals(otherStartFrom.feedRange);
}
return this.eTag.compareTo(otherStartFrom.eTag) == 0 &&
this.feedRange.equals(otherStartFrom.feedRange);
}
@Override
public int hashCode() {
int hash = 1;
hash = (hash * 397) ^ this.feedRange.hashCode();
if (this.eTag != null) {
hash = (hash * 397) ^ this.eTag.hashCode();
}
return hash;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
if (this.eTag != null) {
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
this.eTag);
}
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
} |
Does base class method call need to be "synchronized"/single threaded as well? | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.NOW);
}
} | super.populatePropertyBag(); | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.NOW);
}
} | class ChangeFeedStartFromNowImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromNowImpl() {
super();
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
HttpConstants.HeaderValues.IF_NONE_MATCH_ALL);
}
} | class ChangeFeedStartFromNowImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromNowImpl() {
super();
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
HttpConstants.HeaderValues.IF_NONE_MATCH_ALL);
}
} |
Does base class method call need to be "synchronized"/single threaded as well? | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
com.azure.cosmos.implementation.Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.POINT_IN_TIME);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_POINT_IN_TIME_MS,
this.pointInTime.toEpochMilli());
}
} | synchronized(this) { | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
com.azure.cosmos.implementation.Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.POINT_IN_TIME);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_POINT_IN_TIME_MS,
this.pointInTime.toEpochMilli());
}
} | class ChangeFeedStartFromPointInTimeImpl extends ChangeFeedStartFromInternal {
private final Instant pointInTime;
public ChangeFeedStartFromPointInTimeImpl(Instant pointInTime) {
super();
if (pointInTime == null) {
throw new NullPointerException("pointInTime");
}
this.pointInTime = pointInTime;
}
public Instant getPointInTime() {
return this.pointInTime;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromPointInTimeImpl)) {
return false;
}
ChangeFeedStartFromPointInTimeImpl otherStartFrom = (ChangeFeedStartFromPointInTimeImpl)obj;
return this.pointInTime.equals(otherStartFrom.pointInTime);
}
@Override
public int hashCode() {
return this.pointInTime.hashCode();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
Instant pointInTime = this.getPointInTime();
if (pointInTime != START_FROM_BEGINNING_TIME)
{
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_MODIFIED_SINCE,
Utils.instantAsUTCRFC1123(pointInTime));
}
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} | class ChangeFeedStartFromPointInTimeImpl extends ChangeFeedStartFromInternal {
private final Instant pointInTime;
public ChangeFeedStartFromPointInTimeImpl(Instant pointInTime) {
super();
if (pointInTime == null) {
throw new NullPointerException("pointInTime");
}
this.pointInTime = pointInTime;
}
public Instant getPointInTime() {
return this.pointInTime;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromPointInTimeImpl)) {
return false;
}
ChangeFeedStartFromPointInTimeImpl otherStartFrom = (ChangeFeedStartFromPointInTimeImpl)obj;
return this.pointInTime.equals(otherStartFrom.pointInTime);
}
@Override
public int hashCode() {
return this.pointInTime.hashCode();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
Instant pointInTime = this.getPointInTime();
if (pointInTime != START_FROM_BEGINNING_TIME)
{
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_MODIFIED_SINCE,
Utils.instantAsUTCRFC1123(pointInTime));
}
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} |
if there is any concurrency concern. I suspect the synchronization may need to get extend here as well. any reason this needs to be outside of synchronization scope. also elsewhere for similar cases. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | super.populatePropertyBag(); | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} |
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | super.populatePropertyBag(); | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} |
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.LEASE);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_ETAG,
this.eTag);
this.feedRange.setProperties(
this,
true);
}
} | synchronized(this) { | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.LEASE);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_ETAG,
this.eTag);
this.feedRange.setProperties(
this,
true);
}
} | class ChangeFeedStartFromETagAndFeedRangeImpl extends ChangeFeedStartFromInternal {
private final String eTag;
private final FeedRangeInternal feedRange;
public ChangeFeedStartFromETagAndFeedRangeImpl(String eTag, FeedRangeInternal feedRange) {
super();
checkNotNull(feedRange, "Argument 'feedRange' must not be null");
this.eTag = eTag;
this.feedRange = feedRange;
}
public String getETag() {
return this.eTag;
}
public FeedRangeInternal getFeedRange() {
return this.feedRange;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromETagAndFeedRangeImpl)) {
return false;
}
ChangeFeedStartFromETagAndFeedRangeImpl otherStartFrom =
(ChangeFeedStartFromETagAndFeedRangeImpl)obj;
if (this.eTag == null) {
return otherStartFrom.eTag == null &&
this.feedRange.equals(otherStartFrom.feedRange);
}
return this.eTag.compareTo(otherStartFrom.eTag) == 0 &&
this.feedRange.equals(otherStartFrom.feedRange);
}
@Override
public int hashCode() {
int hash = 1;
hash = (hash * 397) ^ this.feedRange.hashCode();
if (this.eTag != null) {
hash = (hash * 397) ^ this.eTag.hashCode();
}
return hash;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
if (this.eTag != null) {
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
this.eTag);
}
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
} | class ChangeFeedStartFromETagAndFeedRangeImpl extends ChangeFeedStartFromInternal {
private final String eTag;
private final FeedRangeInternal feedRange;
public ChangeFeedStartFromETagAndFeedRangeImpl(String eTag, FeedRangeInternal feedRange) {
super();
checkNotNull(feedRange, "Argument 'feedRange' must not be null");
this.eTag = eTag;
this.feedRange = feedRange;
}
public String getETag() {
return this.eTag;
}
public FeedRangeInternal getFeedRange() {
return this.feedRange;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromETagAndFeedRangeImpl)) {
return false;
}
ChangeFeedStartFromETagAndFeedRangeImpl otherStartFrom =
(ChangeFeedStartFromETagAndFeedRangeImpl)obj;
if (this.eTag == null) {
return otherStartFrom.eTag == null &&
this.feedRange.equals(otherStartFrom.feedRange);
}
return this.eTag.compareTo(otherStartFrom.eTag) == 0 &&
this.feedRange.equals(otherStartFrom.feedRange);
}
@Override
public int hashCode() {
int hash = 1;
hash = (hash * 397) ^ this.feedRange.hashCode();
if (this.eTag != null) {
hash = (hash * 397) ^ this.eTag.hashCode();
}
return hash;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
if (this.eTag != null) {
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
this.eTag);
}
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
} |
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.NOW);
}
} | super.populatePropertyBag(); | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.NOW);
}
} | class ChangeFeedStartFromNowImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromNowImpl() {
super();
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
HttpConstants.HeaderValues.IF_NONE_MATCH_ALL);
}
} | class ChangeFeedStartFromNowImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromNowImpl() {
super();
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
HttpConstants.HeaderValues.IF_NONE_MATCH_ALL);
}
} |
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
com.azure.cosmos.implementation.Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.POINT_IN_TIME);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_POINT_IN_TIME_MS,
this.pointInTime.toEpochMilli());
}
} | synchronized(this) { | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
com.azure.cosmos.implementation.Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.POINT_IN_TIME);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_POINT_IN_TIME_MS,
this.pointInTime.toEpochMilli());
}
} | class ChangeFeedStartFromPointInTimeImpl extends ChangeFeedStartFromInternal {
private final Instant pointInTime;
public ChangeFeedStartFromPointInTimeImpl(Instant pointInTime) {
super();
if (pointInTime == null) {
throw new NullPointerException("pointInTime");
}
this.pointInTime = pointInTime;
}
public Instant getPointInTime() {
return this.pointInTime;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromPointInTimeImpl)) {
return false;
}
ChangeFeedStartFromPointInTimeImpl otherStartFrom = (ChangeFeedStartFromPointInTimeImpl)obj;
return this.pointInTime.equals(otherStartFrom.pointInTime);
}
@Override
public int hashCode() {
return this.pointInTime.hashCode();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
Instant pointInTime = this.getPointInTime();
if (pointInTime != START_FROM_BEGINNING_TIME)
{
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_MODIFIED_SINCE,
Utils.instantAsUTCRFC1123(pointInTime));
}
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} | class ChangeFeedStartFromPointInTimeImpl extends ChangeFeedStartFromInternal {
private final Instant pointInTime;
public ChangeFeedStartFromPointInTimeImpl(Instant pointInTime) {
super();
if (pointInTime == null) {
throw new NullPointerException("pointInTime");
}
this.pointInTime = pointInTime;
}
public Instant getPointInTime() {
return this.pointInTime;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromPointInTimeImpl)) {
return false;
}
ChangeFeedStartFromPointInTimeImpl otherStartFrom = (ChangeFeedStartFromPointInTimeImpl)obj;
return this.pointInTime.equals(otherStartFrom.pointInTime);
}
@Override
public int hashCode() {
return this.pointInTime.hashCode();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
Instant pointInTime = this.getPointInTime();
if (pointInTime != START_FROM_BEGINNING_TIME)
{
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_MODIFIED_SINCE,
Utils.instantAsUTCRFC1123(pointInTime));
}
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} |
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | synchronized(this) { | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} |
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.LEASE);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_ETAG,
this.eTag);
this.feedRange.setProperties(
this,
true);
}
} | synchronized(this) { | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.LEASE);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_ETAG,
this.eTag);
this.feedRange.setProperties(
this,
true);
}
} | class ChangeFeedStartFromETagAndFeedRangeImpl extends ChangeFeedStartFromInternal {
private final String eTag;
private final FeedRangeInternal feedRange;
public ChangeFeedStartFromETagAndFeedRangeImpl(String eTag, FeedRangeInternal feedRange) {
super();
checkNotNull(feedRange, "Argument 'feedRange' must not be null");
this.eTag = eTag;
this.feedRange = feedRange;
}
public String getETag() {
return this.eTag;
}
public FeedRangeInternal getFeedRange() {
return this.feedRange;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromETagAndFeedRangeImpl)) {
return false;
}
ChangeFeedStartFromETagAndFeedRangeImpl otherStartFrom =
(ChangeFeedStartFromETagAndFeedRangeImpl)obj;
if (this.eTag == null) {
return otherStartFrom.eTag == null &&
this.feedRange.equals(otherStartFrom.feedRange);
}
return this.eTag.compareTo(otherStartFrom.eTag) == 0 &&
this.feedRange.equals(otherStartFrom.feedRange);
}
@Override
public int hashCode() {
int hash = 1;
hash = (hash * 397) ^ this.feedRange.hashCode();
if (this.eTag != null) {
hash = (hash * 397) ^ this.eTag.hashCode();
}
return hash;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
if (this.eTag != null) {
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
this.eTag);
}
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
} | class ChangeFeedStartFromETagAndFeedRangeImpl extends ChangeFeedStartFromInternal {
private final String eTag;
private final FeedRangeInternal feedRange;
public ChangeFeedStartFromETagAndFeedRangeImpl(String eTag, FeedRangeInternal feedRange) {
super();
checkNotNull(feedRange, "Argument 'feedRange' must not be null");
this.eTag = eTag;
this.feedRange = feedRange;
}
public String getETag() {
return this.eTag;
}
public FeedRangeInternal getFeedRange() {
return this.feedRange;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromETagAndFeedRangeImpl)) {
return false;
}
ChangeFeedStartFromETagAndFeedRangeImpl otherStartFrom =
(ChangeFeedStartFromETagAndFeedRangeImpl)obj;
if (this.eTag == null) {
return otherStartFrom.eTag == null &&
this.feedRange.equals(otherStartFrom.feedRange);
}
return this.eTag.compareTo(otherStartFrom.eTag) == 0 &&
this.feedRange.equals(otherStartFrom.feedRange);
}
@Override
public int hashCode() {
int hash = 1;
hash = (hash * 397) ^ this.feedRange.hashCode();
if (this.eTag != null) {
hash = (hash * 397) ^ this.eTag.hashCode();
}
return hash;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
if (this.eTag != null) {
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
this.eTag);
}
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
} |
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.NOW);
}
} | super.populatePropertyBag(); | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.NOW);
}
} | class ChangeFeedStartFromNowImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromNowImpl() {
super();
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
HttpConstants.HeaderValues.IF_NONE_MATCH_ALL);
}
} | class ChangeFeedStartFromNowImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromNowImpl() {
super();
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_NONE_MATCH,
HttpConstants.HeaderValues.IF_NONE_MATCH_ALL);
}
} |
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
com.azure.cosmos.implementation.Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.POINT_IN_TIME);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_POINT_IN_TIME_MS,
this.pointInTime.toEpochMilli());
}
} | synchronized(this) { | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
com.azure.cosmos.implementation.Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.POINT_IN_TIME);
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_POINT_IN_TIME_MS,
this.pointInTime.toEpochMilli());
}
} | class ChangeFeedStartFromPointInTimeImpl extends ChangeFeedStartFromInternal {
private final Instant pointInTime;
public ChangeFeedStartFromPointInTimeImpl(Instant pointInTime) {
super();
if (pointInTime == null) {
throw new NullPointerException("pointInTime");
}
this.pointInTime = pointInTime;
}
public Instant getPointInTime() {
return this.pointInTime;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromPointInTimeImpl)) {
return false;
}
ChangeFeedStartFromPointInTimeImpl otherStartFrom = (ChangeFeedStartFromPointInTimeImpl)obj;
return this.pointInTime.equals(otherStartFrom.pointInTime);
}
@Override
public int hashCode() {
return this.pointInTime.hashCode();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
Instant pointInTime = this.getPointInTime();
if (pointInTime != START_FROM_BEGINNING_TIME)
{
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_MODIFIED_SINCE,
Utils.instantAsUTCRFC1123(pointInTime));
}
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} | class ChangeFeedStartFromPointInTimeImpl extends ChangeFeedStartFromInternal {
private final Instant pointInTime;
public ChangeFeedStartFromPointInTimeImpl(Instant pointInTime) {
super();
if (pointInTime == null) {
throw new NullPointerException("pointInTime");
}
this.pointInTime = pointInTime;
}
public Instant getPointInTime() {
return this.pointInTime;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChangeFeedStartFromPointInTimeImpl)) {
return false;
}
ChangeFeedStartFromPointInTimeImpl otherStartFrom = (ChangeFeedStartFromPointInTimeImpl)obj;
return this.pointInTime.equals(otherStartFrom.pointInTime);
}
@Override
public int hashCode() {
return this.pointInTime.hashCode();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
checkNotNull(request, "Argument 'request' must not be null.");
Instant pointInTime = this.getPointInTime();
if (pointInTime != START_FROM_BEGINNING_TIME)
{
request.getHeaders().put(
HttpConstants.HttpHeaders.IF_MODIFIED_SINCE,
Utils.instantAsUTCRFC1123(pointInTime));
}
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} |
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | super.populatePropertyBag(); | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.BEGINNING);
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} | class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromBeginningImpl() {
super();
}
@Override
@Override
public void populateRequest(RxDocumentServiceRequest request) {
}
@Override
public boolean supportsFullFidelityRetention() {
return false;
}
} |
There should be a default value for ApiVersion here in case this is used directly | public TextAnalyticsClientImpl buildClient() {
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
TextAnalyticsClientImpl client = new TextAnalyticsClientImpl(pipeline, serializerAdapter, apiVersion, endpoint);
return client;
} | TextAnalyticsClientImpl client = new TextAnalyticsClientImpl(pipeline, serializerAdapter, apiVersion, endpoint); | public TextAnalyticsClientImpl buildClient() {
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
TextAnalyticsClientImpl client = new TextAnalyticsClientImpl(pipeline, serializerAdapter, apiVersion, endpoint);
return client;
} | class TextAnalyticsClientImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
/** Create an instance of the TextAnalyticsClientImplBuilder. */
public TextAnalyticsClientImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* Client Api Version.
*/
private String apiVersion;
/**
* Sets Client Api Version.
*
* @param apiVersion the apiVersion value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/*
* Supported Cognitive Services endpoints (protocol and hostname, for
* example: https:
*/
private String endpoint;
/**
* Sets Supported Cognitive Services endpoints (protocol and hostname, for example:
* https:
*
* @param endpoint the endpoint value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* The HTTP pipeline to send requests through
*/
private HttpPipeline pipeline;
/**
* Sets The HTTP pipeline to send requests through.
*
* @param pipeline the pipeline value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/*
* The serializer to serialize an object into a string
*/
private SerializerAdapter serializerAdapter;
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
this.serializerAdapter = serializerAdapter;
return this;
}
/*
* The HTTP client used to send the request.
*/
private HttpClient httpClient;
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The configuration store that is used during construction of the service
* client.
*/
private Configuration configuration;
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
private HttpLogOptions httpLogOptions;
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if
* applicable.
*/
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/*
* The list of Http pipeline policies to add.
*/
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Adds a custom Http pipeline policy.
*
* @param customPolicy The custom Http pipeline policy to add.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of TextAnalyticsClientImpl with the provided parameters.
*
* @return an instance of TextAnalyticsClientImpl.
*/
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(
new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.addAll(this.pipelinePolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
} | class TextAnalyticsClientImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
/** Create an instance of the TextAnalyticsClientImplBuilder. */
public TextAnalyticsClientImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* Client Api Version.
*/
private String apiVersion;
/**
* Sets Client Api Version.
*
* @param apiVersion the apiVersion value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/*
* Supported Cognitive Services endpoints (protocol and hostname, for
* example: https:
*/
private String endpoint;
/**
* Sets Supported Cognitive Services endpoints (protocol and hostname, for example:
* https:
*
* @param endpoint the endpoint value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* The HTTP pipeline to send requests through
*/
private HttpPipeline pipeline;
/**
* Sets The HTTP pipeline to send requests through.
*
* @param pipeline the pipeline value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/*
* The serializer to serialize an object into a string
*/
private SerializerAdapter serializerAdapter;
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
this.serializerAdapter = serializerAdapter;
return this;
}
/*
* The HTTP client used to send the request.
*/
private HttpClient httpClient;
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The configuration store that is used during construction of the service
* client.
*/
private Configuration configuration;
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
private HttpLogOptions httpLogOptions;
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if
* applicable.
*/
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/*
* The list of Http pipeline policies to add.
*/
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Adds a custom Http pipeline policy.
*
* @param customPolicy The custom Http pipeline policy to add.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of TextAnalyticsClientImpl with the provided parameters.
*
* @return an instance of TextAnalyticsClientImpl.
*/
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(
new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.addAll(this.pipelinePolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
} |
it is the autogenerated class. The default value is assigned In the convenience level. https://github.com/Azure/azure-sdk-for-java/pull/21028/files?file-filters%5B%5D=.java&hide-deleted-files=true#diff-58e093029f6be3020e93b0556d2f991c51174067b3ceba5d59744230f6a5824aL148 | public TextAnalyticsClientImpl buildClient() {
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
TextAnalyticsClientImpl client = new TextAnalyticsClientImpl(pipeline, serializerAdapter, apiVersion, endpoint);
return client;
} | TextAnalyticsClientImpl client = new TextAnalyticsClientImpl(pipeline, serializerAdapter, apiVersion, endpoint); | public TextAnalyticsClientImpl buildClient() {
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
TextAnalyticsClientImpl client = new TextAnalyticsClientImpl(pipeline, serializerAdapter, apiVersion, endpoint);
return client;
} | class TextAnalyticsClientImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
/** Create an instance of the TextAnalyticsClientImplBuilder. */
public TextAnalyticsClientImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* Client Api Version.
*/
private String apiVersion;
/**
* Sets Client Api Version.
*
* @param apiVersion the apiVersion value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/*
* Supported Cognitive Services endpoints (protocol and hostname, for
* example: https:
*/
private String endpoint;
/**
* Sets Supported Cognitive Services endpoints (protocol and hostname, for example:
* https:
*
* @param endpoint the endpoint value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* The HTTP pipeline to send requests through
*/
private HttpPipeline pipeline;
/**
* Sets The HTTP pipeline to send requests through.
*
* @param pipeline the pipeline value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/*
* The serializer to serialize an object into a string
*/
private SerializerAdapter serializerAdapter;
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
this.serializerAdapter = serializerAdapter;
return this;
}
/*
* The HTTP client used to send the request.
*/
private HttpClient httpClient;
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The configuration store that is used during construction of the service
* client.
*/
private Configuration configuration;
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
private HttpLogOptions httpLogOptions;
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if
* applicable.
*/
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/*
* The list of Http pipeline policies to add.
*/
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Adds a custom Http pipeline policy.
*
* @param customPolicy The custom Http pipeline policy to add.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of TextAnalyticsClientImpl with the provided parameters.
*
* @return an instance of TextAnalyticsClientImpl.
*/
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(
new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.addAll(this.pipelinePolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
} | class TextAnalyticsClientImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
/** Create an instance of the TextAnalyticsClientImplBuilder. */
public TextAnalyticsClientImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* Client Api Version.
*/
private String apiVersion;
/**
* Sets Client Api Version.
*
* @param apiVersion the apiVersion value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/*
* Supported Cognitive Services endpoints (protocol and hostname, for
* example: https:
*/
private String endpoint;
/**
* Sets Supported Cognitive Services endpoints (protocol and hostname, for example:
* https:
*
* @param endpoint the endpoint value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* The HTTP pipeline to send requests through
*/
private HttpPipeline pipeline;
/**
* Sets The HTTP pipeline to send requests through.
*
* @param pipeline the pipeline value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/*
* The serializer to serialize an object into a string
*/
private SerializerAdapter serializerAdapter;
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
this.serializerAdapter = serializerAdapter;
return this;
}
/*
* The HTTP client used to send the request.
*/
private HttpClient httpClient;
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The configuration store that is used during construction of the service
* client.
*/
private Configuration configuration;
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
private HttpLogOptions httpLogOptions;
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if
* applicable.
*/
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/*
* The list of Http pipeline policies to add.
*/
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Adds a custom Http pipeline policy.
*
* @param customPolicy The custom Http pipeline policy to add.
* @return the TextAnalyticsClientImplBuilder.
*/
public TextAnalyticsClientImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of TextAnalyticsClientImpl with the provided parameters.
*
* @return an instance of TextAnalyticsClientImpl.
*/
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(
new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.addAll(this.pipelinePolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
} |
I thought we decided to get the current capabilties and switch to different the capabilities each time? | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
return result.getFinalResult();
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | }) | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
Example for Python: https://github.com/Azure/azure-sdk-for-python/pull/18386/files | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
return result.getFinalResult();
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | }) | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
Can we move the declaration of these two variables outside "this.getClientWithConnectionString"? If yes, we can assert the update actually caused capability change, assertNotEqual. | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities oldPhoneNumberCap = responseAcquiredPhone.getValue().getCapabilities();
PhoneNumberCapabilities newPhoneNumberCap = getNewPhoneCapabilities(oldPhoneNumberCap);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", newPhoneNumberCap)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | PhoneNumberCapabilities newPhoneNumberCap = getNewPhoneCapabilities(oldPhoneNumberCap); | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private PhoneNumberCapabilities getNewPhoneCapabilities(PhoneNumberCapabilities capabilities) {
if (capabilities.getSms() != PhoneNumberCapabilityType.INBOUND_OUTBOUND) {
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
} else {
capabilities.setSms(PhoneNumberCapabilityType.OUTBOUND);
}
if (capabilities.getCalling() != PhoneNumberCapabilityType.OUTBOUND) {
capabilities.setCalling(PhoneNumberCapabilityType.OUTBOUND);
} else {
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
}
return capabilities;
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
Cant because first need to check the current state of the phoneCapabilities | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities oldPhoneNumberCap = responseAcquiredPhone.getValue().getCapabilities();
PhoneNumberCapabilities newPhoneNumberCap = getNewPhoneCapabilities(oldPhoneNumberCap);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", newPhoneNumberCap)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | PhoneNumberCapabilities newPhoneNumberCap = getNewPhoneCapabilities(oldPhoneNumberCap); | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private PhoneNumberCapabilities getNewPhoneCapabilities(PhoneNumberCapabilities capabilities) {
if (capabilities.getSms() != PhoneNumberCapabilityType.INBOUND_OUTBOUND) {
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
} else {
capabilities.setSms(PhoneNumberCapabilityType.OUTBOUND);
}
if (capabilities.getCalling() != PhoneNumberCapabilityType.OUTBOUND) {
capabilities.setCalling(PhoneNumberCapabilityType.OUTBOUND);
} else {
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
}
return capabilities;
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
We also want to check on the status code of the operation and make sure that it is 200 | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | StepVerifier.create( | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
We also want to check on the status code of the operation and make sure that it is 200 | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | .last() | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
We also want to check on the status code of the operation and make sure that it is 200 | public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber acquiredPhoneNumber = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).getFinalResult();
assertNotNull(acquiredPhoneNumber);
} | assertNotNull(acquiredPhoneNumber); | public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber acquiredPhoneNumber = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesSync", true).getFinalResult();
assertNotNull(acquiredPhoneNumber);
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
We also want to check on the status code of the operation and make sure that it is 200 | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber acquiredPhoneNumber = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesSync", true).getFinalResult();
assertNotNull(acquiredPhoneNumber);
} | assertNotNull(acquiredPhoneNumber); | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber acquiredPhoneNumber = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).getFinalResult();
assertNotNull(acquiredPhoneNumber);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
We do not want to set SMS to "inbound" because we also needs this number for SMS tests and so it needs to be "Outbound" or "Inbound+Outbound" | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND); | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
Just checked the PhoneNumberOperationStatus to be success. | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | .last() | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
Just checked the PhoneNumberOperationStatus to be success. | public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber acquiredPhoneNumber = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).getFinalResult();
assertNotNull(acquiredPhoneNumber);
} | assertNotNull(acquiredPhoneNumber); | public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber acquiredPhoneNumber = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesSync", true).getFinalResult();
assertNotNull(acquiredPhoneNumber);
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
PhoneNumberSearchResult searchResult = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true).getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
Just checked the PhoneNumberOperationStatus to be success. | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | StepVerifier.create( | public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberForCapabilities").getPurchasedPhoneNumberWithResponse(phoneNumber)
.flatMap(responseAcquiredPhone -> {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
return beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", capabilities)
.last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasedPhoneNumber> result) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
return result.getFinalResult();
});
})
).assertNext((PurchasedPhoneNumber acquiredPhoneNumber) -> {
assertNotNull(acquiredPhoneNumber);
})
.verifyComplete();
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersAsyncClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumber").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAAD").getPurchasedPhoneNumber(phoneNumber)
)
.assertNext((PurchasedPhoneNumber number) -> {
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponse").getPurchasedPhoneNumberWithResponse(phoneNumber)
)
.assertNext((Response<PurchasedPhoneNumber> response) -> {
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, response.getValue().getPhoneNumber());
assertEquals(COUNTRY_CODE, response.getValue().getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbers").listPurchasedPhoneNumbers().next()
)
.assertNext((PurchasedPhoneNumber number) -> {
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersWithoutOptions(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersWithoutOptions", false).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult();
})
).assertNext((PhoneNumberSearchResult searchResult) -> {
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
StepVerifier.create(
beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbers", true).last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PhoneNumberSearchResult> result) -> {
return result.getFinalResult()
.flatMap((PhoneNumberSearchResult searchResult) -> {
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
return beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbers").last()
.flatMap((AsyncPollResponse<PhoneNumberOperation, PurchasePhoneNumbersResult> purchaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseResult.getStatus());
return beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumber").last();
});
});
})
).assertNext((AsyncPollResponse<PhoneNumberOperation, ReleasePhoneNumberResult> releaseResult) -> {
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseResult.getStatus());
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberNullNumber").getPurchasedPhoneNumber(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponseNullNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseNullNumber").getPurchasedPhoneNumberWithResponse(null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginSearchAvailablePhoneNumbersNullCountryCode(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginSearchAvailablePhoneNumbersNullCountryCode")
.beginSearchAvailablePhoneNumbers(null, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, null, null)
)
.verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void beginUpdatePhoneNumberCapabilitiesNullPhoneNumber(HttpClient httpClient) {
StepVerifier.create(
this.getClientWithConnectionString(httpClient, "beginUpdatePhoneNumberCapabilitiesNullPhoneNumber")
.beginUpdatePhoneNumberCapabilities(null, new PhoneNumberCapabilities())
)
.verifyError();
}
private PollerFlux<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withOptions) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withOptions) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions
));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities
));
}
private PollerFlux<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private PollerFlux<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private PollerFlux<PhoneNumberOperation, PurchasedPhoneNumber> beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, PhoneNumberCapabilities capabilities) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> PollerFlux<T, U> setPollInterval(PollerFlux<T, U> pollerFlux) {
return interceptorManager.isPlaybackMode()
? pollerFlux.setPollInterval(Duration.ofMillis(1))
: pollerFlux.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersAsyncClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private PhoneNumbersAsyncClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
change to ```java this.validator = new AADJwtClaimValidator<>(AADTokenClaim.ISS, validIssuer()); ``` | public AADJwtIssuerValidator() {
this(null);
} | this(null); | public AADJwtIssuerValidator() {
this(null);
} | class AADJwtIssuerValidator implements OAuth2TokenValidator<Jwt> {
private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https:
private static final String STS_WINDOWS_ISSUER = "https:
private static final String STS_CHINA_CLOUD_API_ISSUER = "https:
private final AADJwtClaimValidator<String> validator;
private final AADTrustedIssuerRepository trustedIssuerRepo;
/**
* Constructs a {@link AADJwtIssuerValidator} using the provided parameters
*/
/**
* Constructs a {@link AADJwtIssuerValidator} using the provided parameters
*
* @param aadTrustedIssuerRepository trusted issuer repository.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public AADJwtIssuerValidator(AADTrustedIssuerRepository aadTrustedIssuerRepository) {
if ((trustedIssuerRepo = aadTrustedIssuerRepository) == null) {
this.validator = new AADJwtClaimValidator<>(AADTokenClaim.ISS, validIssuer());
} else {
this.validator = new AADJwtClaimValidator<>(AADTokenClaim.ISS, trustedIssuerRepoValidIssuer());
}
}
private Predicate<String> trustedIssuerRepoValidIssuer() {
return iss -> {
if (iss == null) {
return false;
}
return trustedIssuerRepo.getTrustedIssuers().contains(iss);
};
}
private Predicate<String> validIssuer() {
return iss -> {
if (iss == null) {
return false;
}
return iss.startsWith(LOGIN_MICROSOFT_ONLINE_ISSUER)
|| iss.startsWith(STS_WINDOWS_ISSUER)
|| iss.startsWith(STS_CHINA_CLOUD_API_ISSUER);
};
}
/**
* {@inheritDoc}
*/
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
Assert.notNull(token, "token cannot be null");
return this.validator.validate(token);
}
} | class AADJwtIssuerValidator implements OAuth2TokenValidator<Jwt> {
private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https:
private static final String STS_WINDOWS_ISSUER = "https:
private static final String STS_CHINA_CLOUD_API_ISSUER = "https:
private final AADJwtClaimValidator<String> validator;
private final AADTrustedIssuerRepository trustedIssuerRepo;
/**
* Constructs a {@link AADJwtIssuerValidator} using the provided parameters
*/
/**
* Constructs a {@link AADJwtIssuerValidator} using the provided parameters
*
* @param aadTrustedIssuerRepository trusted issuer repository.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public AADJwtIssuerValidator(AADTrustedIssuerRepository aadTrustedIssuerRepository) {
this.trustedIssuerRepo = aadTrustedIssuerRepository;
this.validator = new AADJwtClaimValidator<>(AADTokenClaim.ISS, trustedIssuerRepoValidIssuer());
}
private Predicate<String> trustedIssuerRepoValidIssuer() {
return iss -> {
if (iss == null) {
return false;
}
if (trustedIssuerRepo == null) {
return iss.startsWith(LOGIN_MICROSOFT_ONLINE_ISSUER)
|| iss.startsWith(STS_WINDOWS_ISSUER)
|| iss.startsWith(STS_CHINA_CLOUD_API_ISSUER);
}
return trustedIssuerRepo.getTrustedIssuers().contains(iss);
};
}
/**
* {@inheritDoc}
*/
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
Assert.notNull(token, "token cannot be null");
return this.validator.validate(token);
}
} |
change to ``` this.validator = new AADJwtClaimValidator<>(AADTokenClaim.ISS, trustedIssuerRepoValidIssuer()); ``` | public AADJwtIssuerValidator(AADTrustedIssuerRepository aadTrustedIssuerRepository) {
if ((trustedIssuerRepo = aadTrustedIssuerRepository) == null) {
this.validator = new AADJwtClaimValidator<>(AADTokenClaim.ISS, validIssuer());
} else {
this.validator = new AADJwtClaimValidator<>(AADTokenClaim.ISS, trustedIssuerRepoValidIssuer());
}
} | } | public AADJwtIssuerValidator(AADTrustedIssuerRepository aadTrustedIssuerRepository) {
this.trustedIssuerRepo = aadTrustedIssuerRepository;
this.validator = new AADJwtClaimValidator<>(AADTokenClaim.ISS, trustedIssuerRepoValidIssuer());
} | class AADJwtIssuerValidator implements OAuth2TokenValidator<Jwt> {
private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https:
private static final String STS_WINDOWS_ISSUER = "https:
private static final String STS_CHINA_CLOUD_API_ISSUER = "https:
private final AADJwtClaimValidator<String> validator;
private final AADTrustedIssuerRepository trustedIssuerRepo;
/**
* Constructs a {@link AADJwtIssuerValidator} using the provided parameters
*/
public AADJwtIssuerValidator() {
this(null);
}
/**
* Constructs a {@link AADJwtIssuerValidator} using the provided parameters
*
* @param aadTrustedIssuerRepository trusted issuer repository.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Predicate<String> trustedIssuerRepoValidIssuer() {
return iss -> {
if (iss == null) {
return false;
}
return trustedIssuerRepo.getTrustedIssuers().contains(iss);
};
}
private Predicate<String> validIssuer() {
return iss -> {
if (iss == null) {
return false;
}
return iss.startsWith(LOGIN_MICROSOFT_ONLINE_ISSUER)
|| iss.startsWith(STS_WINDOWS_ISSUER)
|| iss.startsWith(STS_CHINA_CLOUD_API_ISSUER);
};
}
/**
* {@inheritDoc}
*/
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
Assert.notNull(token, "token cannot be null");
return this.validator.validate(token);
}
} | class AADJwtIssuerValidator implements OAuth2TokenValidator<Jwt> {
private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https:
private static final String STS_WINDOWS_ISSUER = "https:
private static final String STS_CHINA_CLOUD_API_ISSUER = "https:
private final AADJwtClaimValidator<String> validator;
private final AADTrustedIssuerRepository trustedIssuerRepo;
/**
* Constructs a {@link AADJwtIssuerValidator} using the provided parameters
*/
public AADJwtIssuerValidator() {
this(null);
}
/**
* Constructs a {@link AADJwtIssuerValidator} using the provided parameters
*
* @param aadTrustedIssuerRepository trusted issuer repository.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Predicate<String> trustedIssuerRepoValidIssuer() {
return iss -> {
if (iss == null) {
return false;
}
if (trustedIssuerRepo == null) {
return iss.startsWith(LOGIN_MICROSOFT_ONLINE_ISSUER)
|| iss.startsWith(STS_WINDOWS_ISSUER)
|| iss.startsWith(STS_CHINA_CLOUD_API_ISSUER);
}
return trustedIssuerRepo.getTrustedIssuers().contains(iss);
};
}
/**
* {@inheritDoc}
*/
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
Assert.notNull(token, "token cannot be null");
return this.validator.validate(token);
}
} |
Is this missing pageSize as a parameter or is that propagated by the continuation token? #Resolved | public PagedFlux<String> listRepositoryNames() {
return new PagedFlux<>(
(pageSize) -> withContext(context -> listRepositoryNamesSinglePageAsync(pageSize, context)),
(token, pageSize) -> withContext(context -> listRepositoryNamesNextSinglePageAsync(token, context)));
} | (token, pageSize) -> withContext(context -> listRepositoryNamesNextSinglePageAsync(token, context))); | public PagedFlux<String> listRepositoryNames() {
return new PagedFlux<>(
(pageSize) -> withContext(context -> listRepositoryNamesSinglePageAsync(pageSize, context)),
(token, pageSize) -> withContext(context -> listRepositoryNamesNextSinglePageAsync(token, context)));
} | class ContainerRegistryAsyncClient {
private final ContainerRegistryImpl registryImplClient;
private final ContainerRegistriesImpl registriesImplClient;
private final HttpPipeline httpPipeline;
private final String endpoint;
private final String apiVersion;
private final String registryName;
private final String loginServer;
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;
try {
URL endpointUrl = new URL(endpoint);
this.loginServer = endpointUrl.getHost();
this.registryName = this.loginServer.indexOf(".") == -1 ? null : this.loginServer.split("\\.")[0];
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
}
/**
* This method returns the login server associated with the given client.
* @return The full login server name including the namespace.
*/
public String getLoginServer() {
return this.loginServer;
}
/**
* This method returns the name of the registry.
* @return The registry name without the namespace.
*/
public String getName() {
return this.registryName;
}
/**
* This method returns the complete registry endpoint.
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* List all the repository names in this registry.
*
* @return list of repository names.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
Mono<PagedResponse<String>> listRepositoryNamesSinglePageAsync(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>> listRepositoryNamesNextSinglePageAsync(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 repository 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 repository) {
return withContext(context -> deleteRepositoryWithResponse(repository, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String repository, Context context) {
try {
if (repository == null) {
return monoError(logger, new NullPointerException("'name' cannot be null."));
}
return this.registriesImplClient.deleteRepositoryWithResponseAsync(repository, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by 'name'.
*
* @param repository 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 repository) {
return withContext(context -> this.deleteRepository(repository, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
return this.deleteRepositoryWithResponse(name, context).map(Response::getValue);
}
/**
* Get an instance of container repository class.
*
* @param repository Name of the repository (including the namespace).
* @return repository client.
*/
public ContainerRepositoryAsync getRepository(String repository) {
return new ContainerRepositoryAsync(repository, httpPipeline, endpoint, apiVersion);
}
/**
* Get an instance of registry artifact class.
*
* @param repositoryName Name of the repository (including the namespace).
* @param tagOrDigest Tag or digest associated with the artifact.
* @return repository client.
*/
public RegistryArtifactAsync getArtifact(String repositoryName, String tagOrDigest) {
return new RegistryArtifactAsync(repositoryName, tagOrDigest, httpPipeline, 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 String registryName;
private final String loginServer;
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;
try {
URL endpointUrl = new URL(endpoint);
this.loginServer = endpointUrl.getHost();
this.registryName = this.loginServer.split("\\.")[0];
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
}
/**
* This method returns the login server associated with the given client.
* @return The full login server name including the namespace.
*/
public String getLoginServer() {
return this.loginServer;
}
/**
* This method returns the name of the registry.
* @return The registry name without the namespace.
*/
public String getName() {
return this.registryName;
}
/**
* This method returns the complete registry endpoint.
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* List all the repository names in this registry.
*
* @return list of repository names.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<String> listRepositoryNames(Context context) {
return new PagedFlux<>(
(pageSize) -> listRepositoryNamesSinglePageAsync(pageSize, context),
(token, pageSize) -> listRepositoryNamesNextSinglePageAsync(token, context));
}
Mono<PagedResponse<String>> listRepositoryNamesSinglePageAsync(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>> listRepositoryNamesNextSinglePageAsync(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 'repositoryName'.
*
* @param repositoryName 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 repositoryName) {
return withContext(context -> deleteRepositoryWithResponse(repositoryName, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String repositoryName, Context context) {
try {
if (repositoryName == null) {
return monoError(logger, new NullPointerException("'repositoryName' cannot be null."));
}
return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by 'repositoryName'.
*
* @param repositoryName 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 repositoryName) {
return withContext(context -> this.deleteRepository(repositoryName, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String repositoryName, Context context) {
return this.deleteRepositoryWithResponse(repositoryName, context).map(Response::getValue);
}
/**
* Get an instance of container repository class.
*
* @param repositoryName Name of the repository (including the namespace).
* @return repository client.
*/
public ContainerRepositoryAsync getRepository(String repositoryName) {
return new ContainerRepositoryAsync(repositoryName, httpPipeline, endpoint, apiVersion);
}
/**
* Get an instance of registry artifact class.
*
* @param repositoryName Name of the repository (including the namespace).
* @param tagOrDigest Tag or digest associated with the artifact.
* @return repository client.
*/
public RegistryArtifactAsync getArtifact(String repositoryName, String tagOrDigest) {
return new RegistryArtifactAsync(repositoryName, tagOrDigest, httpPipeline, endpoint, apiVersion);
}
} |
It is propogated by the continuation token. | public PagedFlux<String> listRepositoryNames() {
return new PagedFlux<>(
(pageSize) -> withContext(context -> listRepositoryNamesSinglePageAsync(pageSize, context)),
(token, pageSize) -> withContext(context -> listRepositoryNamesNextSinglePageAsync(token, context)));
} | (token, pageSize) -> withContext(context -> listRepositoryNamesNextSinglePageAsync(token, context))); | public PagedFlux<String> listRepositoryNames() {
return new PagedFlux<>(
(pageSize) -> withContext(context -> listRepositoryNamesSinglePageAsync(pageSize, context)),
(token, pageSize) -> withContext(context -> listRepositoryNamesNextSinglePageAsync(token, context)));
} | class ContainerRegistryAsyncClient {
private final ContainerRegistryImpl registryImplClient;
private final ContainerRegistriesImpl registriesImplClient;
private final HttpPipeline httpPipeline;
private final String endpoint;
private final String apiVersion;
private final String registryName;
private final String loginServer;
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;
try {
URL endpointUrl = new URL(endpoint);
this.loginServer = endpointUrl.getHost();
this.registryName = this.loginServer.indexOf(".") == -1 ? null : this.loginServer.split("\\.")[0];
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
}
/**
* This method returns the login server associated with the given client.
* @return The full login server name including the namespace.
*/
public String getLoginServer() {
return this.loginServer;
}
/**
* This method returns the name of the registry.
* @return The registry name without the namespace.
*/
public String getName() {
return this.registryName;
}
/**
* This method returns the complete registry endpoint.
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* List all the repository names in this registry.
*
* @return list of repository names.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
Mono<PagedResponse<String>> listRepositoryNamesSinglePageAsync(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>> listRepositoryNamesNextSinglePageAsync(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 repository 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 repository) {
return withContext(context -> deleteRepositoryWithResponse(repository, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String repository, Context context) {
try {
if (repository == null) {
return monoError(logger, new NullPointerException("'name' cannot be null."));
}
return this.registriesImplClient.deleteRepositoryWithResponseAsync(repository, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by 'name'.
*
* @param repository 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 repository) {
return withContext(context -> this.deleteRepository(repository, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
return this.deleteRepositoryWithResponse(name, context).map(Response::getValue);
}
/**
* Get an instance of container repository class.
*
* @param repository Name of the repository (including the namespace).
* @return repository client.
*/
public ContainerRepositoryAsync getRepository(String repository) {
return new ContainerRepositoryAsync(repository, httpPipeline, endpoint, apiVersion);
}
/**
* Get an instance of registry artifact class.
*
* @param repositoryName Name of the repository (including the namespace).
* @param tagOrDigest Tag or digest associated with the artifact.
* @return repository client.
*/
public RegistryArtifactAsync getArtifact(String repositoryName, String tagOrDigest) {
return new RegistryArtifactAsync(repositoryName, tagOrDigest, httpPipeline, 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 String registryName;
private final String loginServer;
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;
try {
URL endpointUrl = new URL(endpoint);
this.loginServer = endpointUrl.getHost();
this.registryName = this.loginServer.split("\\.")[0];
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
}
/**
* This method returns the login server associated with the given client.
* @return The full login server name including the namespace.
*/
public String getLoginServer() {
return this.loginServer;
}
/**
* This method returns the name of the registry.
* @return The registry name without the namespace.
*/
public String getName() {
return this.registryName;
}
/**
* This method returns the complete registry endpoint.
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* List all the repository names in this registry.
*
* @return list of repository names.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<String> listRepositoryNames(Context context) {
return new PagedFlux<>(
(pageSize) -> listRepositoryNamesSinglePageAsync(pageSize, context),
(token, pageSize) -> listRepositoryNamesNextSinglePageAsync(token, context));
}
Mono<PagedResponse<String>> listRepositoryNamesSinglePageAsync(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>> listRepositoryNamesNextSinglePageAsync(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 'repositoryName'.
*
* @param repositoryName 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 repositoryName) {
return withContext(context -> deleteRepositoryWithResponse(repositoryName, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String repositoryName, Context context) {
try {
if (repositoryName == null) {
return monoError(logger, new NullPointerException("'repositoryName' cannot be null."));
}
return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by 'repositoryName'.
*
* @param repositoryName 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 repositoryName) {
return withContext(context -> this.deleteRepository(repositoryName, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String repositoryName, Context context) {
return this.deleteRepositoryWithResponse(repositoryName, context).map(Response::getValue);
}
/**
* Get an instance of container repository class.
*
* @param repositoryName Name of the repository (including the namespace).
* @return repository client.
*/
public ContainerRepositoryAsync getRepository(String repositoryName) {
return new ContainerRepositoryAsync(repositoryName, httpPipeline, endpoint, apiVersion);
}
/**
* Get an instance of registry artifact class.
*
* @param repositoryName Name of the repository (including the namespace).
* @param tagOrDigest Tag or digest associated with the artifact.
* @return repository client.
*/
public RegistryArtifactAsync getArtifact(String repositoryName, String tagOrDigest) {
return new RegistryArtifactAsync(repositoryName, tagOrDigest, httpPipeline, endpoint, apiVersion);
}
} |
Since `continuationPredicate` is package-private, this will not be accessible to any sub-classes outside of this package. | protected ContinuablePagedFlux(Predicate<C> continuationPredicate) {
this.continuationPredicate = (continuationPredicate == null) ? Objects::nonNull : continuationPredicate;
} | this.continuationPredicate = (continuationPredicate == null) ? Objects::nonNull : continuationPredicate; | protected ContinuablePagedFlux(Predicate<C> continuationPredicate) {
this.continuationPredicate = (continuationPredicate == null) ? Objects::nonNull : continuationPredicate;
} | class ContinuablePagedFlux<C, T, P extends ContinuablePage<C, T>> extends Flux<T> {
final Predicate<C> continuationPredicate;
/**
* Creates an instance of ContinuablePagedFlux.
* <p>
* Continuation completes when the last returned continuation token is null.
*/
protected ContinuablePagedFlux() {
this(Objects::nonNull);
}
/**
* Creates an instance of ContinuablePagedFlux.
* <p>
* If {@code continuationPredicate} is null then the predicate will only check if the continuation token is
* non-null.
*
* @param continuationPredicate A predicate which determines if paging should continue.
*/
/**
* Gets a {@link Flux} of {@link ContinuablePage} starting at the first page.
*
* @return A {@link Flux} of {@link ContinuablePage}.
*/
public abstract Flux<P> byPage();
/**
* Gets a {@link Flux} of {@link ContinuablePage} beginning at the page identified by the given continuation token.
*
* @param continuationToken A continuation token identifying the page to select.
* @return A {@link Flux} of {@link ContinuablePage}.
*/
public abstract Flux<P> byPage(C continuationToken);
/**
* Gets a {@link Flux} of {@link ContinuablePage} starting at the first page requesting each page to contain a
* number of elements equal to the preferred page size.
* <p>
* The service may or may not honor the preferred page size therefore the client <em>MUST</em> be prepared to handle
* pages with different page sizes.
*
* @param preferredPageSize The preferred page size.
* @return A {@link Flux} of {@link ContinuablePage}.
*/
public abstract Flux<P> byPage(int preferredPageSize);
/**
* Gets a {@link Flux} of {@link ContinuablePage} beginning at the page identified by the given continuation token
* requesting each page to contain the number of elements equal to the preferred page size.
* <p>
* The service may or may not honor the preferred page size therefore the client <em>MUST</em> be prepared to handle
* pages with different page sizes.
*
* @param continuationToken A continuation token identifying the page to select.
* @param preferredPageSize The preferred page size.
* @return A {@link Flux} of {@link ContinuablePage}.
*/
public abstract Flux<P> byPage(C continuationToken, int preferredPageSize);
} | class ContinuablePagedFlux<C, T, P extends ContinuablePage<C, T>> extends Flux<T> {
private final Predicate<C> continuationPredicate;
/**
* Creates an instance of ContinuablePagedFlux.
* <p>
* Continuation completes when the last returned continuation token is null.
*/
public ContinuablePagedFlux() {
this(Objects::nonNull);
}
/**
* Creates an instance of ContinuablePagedFlux.
* <p>
* If {@code continuationPredicate} is null then the predicate will only check if the continuation token is
* non-null.
*
* @param continuationPredicate A predicate which determines if paging should continue.
*/
/**
* Gets a {@link Flux} of {@link ContinuablePage} starting at the first page.
*
* @return A {@link Flux} of {@link ContinuablePage}.
*/
public abstract Flux<P> byPage();
/**
* Gets a {@link Flux} of {@link ContinuablePage} beginning at the page identified by the given continuation token.
*
* @param continuationToken A continuation token identifying the page to select.
* @return A {@link Flux} of {@link ContinuablePage}.
*/
public abstract Flux<P> byPage(C continuationToken);
/**
* Gets a {@link Flux} of {@link ContinuablePage} starting at the first page requesting each page to contain a
* number of elements equal to the preferred page size.
* <p>
* The service may or may not honor the preferred page size therefore the client <em>MUST</em> be prepared to handle
* pages with different page sizes.
*
* @param preferredPageSize The preferred page size.
* @return A {@link Flux} of {@link ContinuablePage}.
*/
public abstract Flux<P> byPage(int preferredPageSize);
/**
* Gets a {@link Flux} of {@link ContinuablePage} beginning at the page identified by the given continuation token
* requesting each page to contain the number of elements equal to the preferred page size.
* <p>
* The service may or may not honor the preferred page size therefore the client <em>MUST</em> be prepared to handle
* pages with different page sizes.
*
* @param continuationToken A continuation token identifying the page to select.
* @param preferredPageSize The preferred page size.
* @return A {@link Flux} of {@link ContinuablePage}.
*/
public abstract Flux<P> byPage(C continuationToken, int preferredPageSize);
/**
* Gets the {@link Predicate} that determines if paging should continue.
*
* @return The {@link Predicate} that determines if paging should continue.
*/
protected final Predicate<C> getContinuationPredicate() {
return continuationPredicate;
}
} |
small thing, but might be worth renaming the folder where the sample files live to identity documents | public static void main(final String[] args) throws IOException {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
File licenseDocumentFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/java/"
+ "sample-forms/ID documents/license.jpg");
byte[] fileContent = Files.readAllBytes(licenseDocumentFile.toPath());
InputStream targetStream = new ByteArrayInputStream(fileContent);
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> analyzeIdentityDocumentPoller =
client.beginRecognizeIdentityDocuments(targetStream, licenseDocumentFile.length());
List<RecognizedForm> identityDocumentResults = analyzeIdentityDocumentPoller.getFinalResult();
for (int i = 0; i < identityDocumentResults.size(); i++) {
RecognizedForm recognizedForm = identityDocumentResults.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField addressField = recognizedFields.get("Address");
if (addressField != null) {
if (FieldValueType.STRING == addressField.getValue().getValueType()) {
String address = addressField.getValue().asString();
System.out.printf("Address: %s, confidence: %.2f%n",
address, addressField.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 dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
FormField 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, documentNumberField.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 regionField = recognizedFields.get("Region");
if (regionField != null) {
if (FieldValueType.STRING == regionField.getValue().getValueType()) {
String region = regionField.getValue().asString();
System.out.printf("Region: %s, confidence: %.2f%n",
region, regionField.getConfidence());
}
}
}
} | + "sample-forms/ID documents/license.jpg"); | public static void main(final String[] args) throws IOException {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
File licenseDocumentFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/java/"
+ "sample-forms/identityDocuments/license.jpg");
byte[] fileContent = Files.readAllBytes(licenseDocumentFile.toPath());
InputStream targetStream = new ByteArrayInputStream(fileContent);
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> analyzeIdentityDocumentPoller =
client.beginRecognizeIdentityDocuments(targetStream, licenseDocumentFile.length());
List<RecognizedForm> identityDocumentResults = analyzeIdentityDocumentPoller.getFinalResult();
for (int i = 0; i < identityDocumentResults.size(); i++) {
RecognizedForm recognizedForm = identityDocumentResults.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField addressField = recognizedFields.get("Address");
if (addressField != null) {
if (FieldValueType.STRING == addressField.getValue().getValueType()) {
String address = addressField.getValue().asString();
System.out.printf("Address: %s, confidence: %.2f%n",
address, addressField.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 dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
FormField 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, documentNumberField.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 regionField = recognizedFields.get("Region");
if (regionField != null) {
if (FieldValueType.STRING == regionField.getValue().getValueType()) {
String region = regionField.getValue().asString();
System.out.printf("Region: %s, confidence: %.2f%n",
region, regionField.getConfidence());
}
}
}
} | class RecognizeIdentityDocuments {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*
* @throws IOException from reading file.
*/
} | class RecognizeIdentityDocuments {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*
* @throws IOException from reading file.
*/
} |
Isn't this change also in the other PR? | private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException {
final String path = methodParser.setPath(args);
final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path);
final UrlBuilder urlBuilder;
if (pathUrlBuilder.getScheme() != null) {
urlBuilder = pathUrlBuilder;
} else {
urlBuilder = new UrlBuilder();
methodParser.setSchemeAndHost(args, urlBuilder);
if (path != null && !path.isEmpty() && !"/".equals(path)) {
String hostPath = urlBuilder.getPath();
if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(":
urlBuilder.setPath(path);
} else {
if (path.startsWith("/")) {
urlBuilder.setPath(hostPath + path);
} else {
urlBuilder.setPath(hostPath + "/" + path);
}
}
}
}
methodParser.setEncodedQueryParameters(args, urlBuilder);
final URL url = urlBuilder.toUrl();
final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url),
methodParser, args);
HttpHeaders httpHeaders = request.getHeaders();
methodParser.setHeaders(args, httpHeaders);
return request;
} | } | private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException {
final String path = methodParser.setPath(args);
final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path);
final UrlBuilder urlBuilder;
if (pathUrlBuilder.getScheme() != null) {
urlBuilder = pathUrlBuilder;
} else {
urlBuilder = new UrlBuilder();
methodParser.setSchemeAndHost(args, urlBuilder);
if (path != null && !path.isEmpty() && !"/".equals(path)) {
String hostPath = urlBuilder.getPath();
if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(":
urlBuilder.setPath(path);
} else {
if (path.startsWith("/")) {
urlBuilder.setPath(hostPath + path);
} else {
urlBuilder.setPath(hostPath + "/" + path);
}
}
}
}
methodParser.setEncodedQueryParameters(args, urlBuilder);
final URL url = urlBuilder.toUrl();
final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url),
methodParser, args);
HttpHeaders httpHeaders = request.getHeaders();
methodParser.setHeaders(args, httpHeaders);
return request;
} | class RestProxy implements InvocationHandler {
private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0);
private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes.";
private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes.";
private static final String MUST_IMPLEMENT_PAGE_ERROR =
"Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class;
private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache();
private final ClientLogger logger = new ClientLogger(RestProxy.class);
private final HttpPipeline httpPipeline;
private final SerializerAdapter serializer;
private final SwaggerInterfaceParser interfaceParser;
private final HttpResponseDecoder decoder;
/**
* Create a RestProxy.
*
* @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests.
* @param serializer the serializer that will be used to convert response bodies to POJOs.
* @param interfaceParser the parser that contains information about the interface describing REST API methods that
* this RestProxy "implements".
*/
private RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) {
this.httpPipeline = httpPipeline;
this.serializer = serializer;
this.interfaceParser = interfaceParser;
this.decoder = new HttpResponseDecoder(this.serializer);
}
/**
* Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this
* RestProxy was created to "implement".
*
* @param method the method to get a SwaggerMethodParser for
* @return the SwaggerMethodParser for the provided method
*/
private SwaggerMethodParser getMethodParser(Method method) {
return interfaceParser.getMethodParser(method);
}
/**
* Send the provided request asynchronously, applying any request policies provided to the HttpClient instance.
*
* @param request the HTTP request to send
* @param contextData the context
* @return a {@link Mono} that emits HttpResponse asynchronously
*/
public Mono<HttpResponse> send(HttpRequest request, Context contextData) {
return httpPipeline.send(request, contextData);
}
@Override
public Object invoke(Object proxy, final Method method, Object[] args) {
try {
if (method.isAnnotationPresent(ResumeOperation.class)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new Exception("The resume operation isn't supported.")));
}
final SwaggerMethodParser methodParser = getMethodParser(method);
final HttpRequest request = createHttpRequest(methodParser, args);
Context context = methodParser.setContext(args)
.addData("caller-method", methodParser.getFullyQualifiedMethodName())
.addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType()));
context = startTracingSpan(method, context);
if (request.getBody() != null) {
request.setBody(validateLength(request));
}
final Mono<HttpResponse> asyncResponse = send(request, context);
Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser);
return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context);
} catch (IOException e) {
throw logger.logExceptionAsError(Exceptions.propagate(e));
}
}
static Flux<ByteBuffer> validateLength(final HttpRequest request) {
final Flux<ByteBuffer> bbFlux = request.getBody();
if (bbFlux == null) {
return Flux.empty();
}
final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length"));
return Flux.defer(() -> {
final long[] currentTotalLength = new long[1];
return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> {
if (buffer == null) {
return;
}
if (buffer == VALIDATION_BUFFER) {
if (expectedLength != currentTotalLength[0]) {
sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL,
currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength));
} else {
sink.complete();
}
return;
}
currentTotalLength[0] += buffer.remaining();
if (currentTotalLength[0] > expectedLength) {
sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE,
currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength));
return;
}
sink.next(buffer);
});
});
}
/**
* Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing
* additional context information.
*
* @param method Service method being called.
* @param context Context information about the current service call.
* @return The updated context containing the span context.
*/
private Context startTracingSpan(Method method, Context context) {
boolean disableTracing = (boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false);
if (!TracerProxy.isTracingEnabled() || disableTracing) {
return context;
}
String spanName = String.format("%s.%s", interfaceParser.getServiceName(), method.getName());
context = TracerProxy.setSpanName(spanName, context);
return TracerProxy.start(spanName, context);
}
/**
* Create a HttpRequest for the provided Swagger method using the provided arguments.
*
* @param methodParser the Swagger method parser to use
* @param args the arguments to use to populate the method's annotation values
* @return a HttpRequest
* @throws IOException thrown if the body contents cannot be serialized
*/
@SuppressWarnings("unchecked")
private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser,
final Object[] args) throws IOException {
final Object bodyContentObject = methodParser.setBody(args);
if (bodyContentObject == null) {
request.getHeaders().set("Content-Length", "0");
} else {
String contentType = methodParser.getBodyContentType();
if (contentType == null || contentType.isEmpty()) {
if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) {
contentType = ContentType.APPLICATION_OCTET_STREAM;
} else {
contentType = ContentType.APPLICATION_JSON;
}
}
request.getHeaders().set("Content-Type", contentType);
boolean isJson = false;
final String[] contentTypeParts = contentType.split(";");
for (final String contentTypePart : contentTypeParts) {
if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) {
isJson = true;
break;
}
}
if (isJson) {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size()))));
} else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) {
request.setBody((Flux<ByteBuffer>) bodyContentObject);
} else if (bodyContentObject instanceof byte[]) {
request.setBody((byte[]) bodyContentObject);
} else if (bodyContentObject instanceof String) {
final String bodyContentString = (String) bodyContentObject;
if (!bodyContentString.isEmpty()) {
request.setBody(bodyContentString);
}
} else if (bodyContentObject instanceof ByteBuffer) {
request.setBody(Flux.just((ByteBuffer) bodyContentObject));
} else {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size()))));
}
}
return request;
}
private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse,
final SwaggerMethodParser methodParser) {
return asyncDecodedResponse
.flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser));
}
private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception,
final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) {
final int responseStatusCode = httpResponse.getStatusCode();
final String contentType = httpResponse.getHeaderValue("Content-Type");
final String bodyRepresentation;
if ("application/octet-stream".equalsIgnoreCase(contentType)) {
bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)";
} else {
bodyRepresentation = responseContent == null || responseContent.length == 0
? "(empty body)"
: "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\"";
}
Exception result;
try {
final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType()
.getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType());
result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation,
httpResponse, responseDecodedContent);
} catch (ReflectiveOperationException e) {
String message = "Status code " + responseStatusCode + ", but an instance of "
+ exception.getExceptionType().getCanonicalName() + " cannot be created."
+ " Response body: " + bodyRepresentation;
result = new IOException(message, e);
}
return result;
}
/**
* Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status
* code' OR (2) emits provided response if it's status code ia allowed.
*
* 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[]
* of additional allowed status codes.
*
* @param decodedResponse The HttpResponse to check.
* @param methodParser The method parser that contains information about the service interface method that initiated
* the HTTP request.
* @return An async-version of the provided decodedResponse.
*/
private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse,
final SwaggerMethodParser methodParser) {
final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode();
final Mono<HttpDecodedResponse> asyncResult;
if (!methodParser.isExpectedResponseStatusCode(responseStatusCode)) {
Mono<byte[]> bodyAsBytes = decodedResponse.getSourceResponse().getBodyAsByteArray();
asyncResult = bodyAsBytes.flatMap((Function<byte[], Mono<HttpDecodedResponse>>) responseContent -> {
Mono<Object> decodedErrorBody = decodedResponse.getDecodedBody(responseContent);
return decodedErrorBody
.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> {
Throwable exception = instantiateUnexpectedException(
methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseContent, responseDecodedErrorObject);
return Mono.error(exception);
})
.switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> {
Throwable exception = instantiateUnexpectedException(
methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseContent, null);
return Mono.error(exception);
}));
}).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> {
Throwable exception =
instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), null, null);
return Mono.error(exception);
}));
} else {
asyncResult = Mono.just(decodedResponse);
}
return asyncResult;
}
private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser,
final Type entityType) {
if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) {
final Type bodyType = TypeUtil.getRestResponseBodyType(entityType);
if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) {
return response.getSourceResponse().getBody().ignoreElements()
.then(createResponse(response, entityType, null));
} else {
return handleBodyReturnType(response, methodParser, bodyType)
.flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject))
.switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response,
entityType, null)));
}
} else {
return handleBodyReturnType(response, methodParser, entityType);
}
}
@SuppressWarnings("unchecked")
private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) {
Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType);
if (cls.equals(Response.class)) {
cls = (Class<? extends Response<?>>) (Object) ResponseBase.class;
} else if (cls.equals(PagedResponse.class)) {
cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class;
if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) {
return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR));
}
}
return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(cls))
.switchIfEmpty(Mono.error(new RuntimeException("Cannot find suitable constructor for class " + cls)))
.flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject));
}
private Mono<?> handleBodyReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Mono<?> asyncResult;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(
entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
asyncResult = Mono.just(isSuccess);
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray();
if (returnValueWireType == Base64Url.class) {
responseBodyBytesAsync =
responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes());
}
asyncResult = responseBodyBytesAsync;
} else if (FluxUtil.isFluxByteBuffer(entityType)) {
asyncResult = Mono.just(response.getSourceResponse().getBody());
} else {
asyncResult = response.getDecodedBody((byte[]) null);
}
return asyncResult;
}
/**
* Handle the provided asynchronous HTTP response and return the deserialized value.
*
* @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request
* @param methodParser the SwaggerMethodParser that the request originates from
* @param returnType the type of value that will be returned
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return the deserialized result
*/
private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse,
final SwaggerMethodParser methodParser,
final Type returnType,
final Context context) {
final Mono<HttpDecodedResponse> asyncExpectedResponse =
ensureExpectedStatus(asyncHttpDecodedResponse, methodParser)
.doOnEach(RestProxy::endTracingSpan)
.contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context));
final Object result;
if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) {
final Type monoTypeParam = TypeUtil.getTypeArgument(returnType);
if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) {
result = asyncExpectedResponse.then();
} else {
result = asyncExpectedResponse.flatMap(response ->
handleRestResponseReturnType(response, methodParser, monoTypeParam));
}
} else if (FluxUtil.isFluxByteBuffer(returnType)) {
result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody());
} else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType,
Void.class)) {
asyncExpectedResponse.block();
result = null;
} else {
result = asyncExpectedResponse
.flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType))
.block();
}
return result;
}
private static void endTracingSpan(Signal<HttpDecodedResponse> signal) {
if (!TracerProxy.isTracingEnabled()) {
return;
}
if (signal.isOnComplete() || signal.isOnSubscribe()) {
return;
}
ContextView context = signal.getContextView();
Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT");
boolean disableTracing = context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false);
if (!tracingContext.isPresent() || disableTracing) {
return;
}
int statusCode = 0;
HttpDecodedResponse httpDecodedResponse;
Throwable throwable = null;
if (signal.hasValue()) {
httpDecodedResponse = signal.get();
statusCode = httpDecodedResponse.getSourceResponse().getStatusCode();
} else if (signal.hasError()) {
throwable = signal.getThrowable();
if (throwable instanceof HttpResponseException) {
HttpResponseException exception = (HttpResponseException) throwable;
statusCode = exception.getResponse().getStatusCode();
}
}
TracerProxy.end(statusCode, throwable, tracingContext.get());
}
/**
* Create an instance of the default serializer.
*
* @return the default serializer
*/
private static SerializerAdapter createDefaultSerializer() {
return JacksonAdapter.createDefaultSerializerAdapter();
}
/**
* Create the default HttpPipeline.
*
* @return the default HttpPipeline
*/
private static HttpPipeline createDefaultPipeline() {
return createDefaultPipeline(null);
}
/**
* Create the default HttpPipeline.
*
* @param credentialsPolicy the credentials policy factory to use to apply authentication to the pipeline
* @return the default HttpPipeline
*/
private static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy());
policies.add(new RetryPolicy());
policies.add(new CookiePolicy());
if (credentialsPolicy != null) {
policies.add(credentialsPolicy);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param <A> the type of the Swagger interface
* @return a proxy implementation of the provided Swagger interface
*/
public static <A> A create(Class<A> swaggerInterface) {
return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer());
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests
* @param <A> the type of the Swagger interface
* @return a proxy implementation of the provided Swagger interface
*/
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) {
return create(swaggerInterface, httpPipeline, createDefaultSerializer());
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests
* @param serializer the serializer that will be used to convert POJOs to and from request and response bodies
* @param <A> the type of the Swagger interface.
* @return a proxy implementation of the provided Swagger interface
*/
@SuppressWarnings("unchecked")
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) {
final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer);
final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser);
return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface},
restProxy);
}
} | class RestProxy implements InvocationHandler {
private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0);
private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes.";
private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes.";
private static final String MUST_IMPLEMENT_PAGE_ERROR =
"Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class;
private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache();
private final ClientLogger logger = new ClientLogger(RestProxy.class);
private final HttpPipeline httpPipeline;
private final SerializerAdapter serializer;
private final SwaggerInterfaceParser interfaceParser;
private final HttpResponseDecoder decoder;
/**
* Create a RestProxy.
*
* @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests.
* @param serializer the serializer that will be used to convert response bodies to POJOs.
* @param interfaceParser the parser that contains information about the interface describing REST API methods that
* this RestProxy "implements".
*/
private RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) {
this.httpPipeline = httpPipeline;
this.serializer = serializer;
this.interfaceParser = interfaceParser;
this.decoder = new HttpResponseDecoder(this.serializer);
}
/**
* Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this
* RestProxy was created to "implement".
*
* @param method the method to get a SwaggerMethodParser for
* @return the SwaggerMethodParser for the provided method
*/
private SwaggerMethodParser getMethodParser(Method method) {
return interfaceParser.getMethodParser(method);
}
/**
* Send the provided request asynchronously, applying any request policies provided to the HttpClient instance.
*
* @param request the HTTP request to send
* @param contextData the context
* @return a {@link Mono} that emits HttpResponse asynchronously
*/
public Mono<HttpResponse> send(HttpRequest request, Context contextData) {
return httpPipeline.send(request, contextData);
}
@Override
public Object invoke(Object proxy, final Method method, Object[] args) {
try {
if (method.isAnnotationPresent(ResumeOperation.class)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new Exception("The resume operation isn't supported.")));
}
final SwaggerMethodParser methodParser = getMethodParser(method);
final HttpRequest request = createHttpRequest(methodParser, args);
Context context = methodParser.setContext(args)
.addData("caller-method", methodParser.getFullyQualifiedMethodName())
.addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType()));
context = startTracingSpan(method, context);
if (request.getBody() != null) {
request.setBody(validateLength(request));
}
final Mono<HttpResponse> asyncResponse = send(request, context);
Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser);
return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context);
} catch (IOException e) {
throw logger.logExceptionAsError(Exceptions.propagate(e));
}
}
static Flux<ByteBuffer> validateLength(final HttpRequest request) {
final Flux<ByteBuffer> bbFlux = request.getBody();
if (bbFlux == null) {
return Flux.empty();
}
final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length"));
return Flux.defer(() -> {
final long[] currentTotalLength = new long[1];
return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> {
if (buffer == null) {
return;
}
if (buffer == VALIDATION_BUFFER) {
if (expectedLength != currentTotalLength[0]) {
sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL,
currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength));
} else {
sink.complete();
}
return;
}
currentTotalLength[0] += buffer.remaining();
if (currentTotalLength[0] > expectedLength) {
sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE,
currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength));
return;
}
sink.next(buffer);
});
});
}
/**
* Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing
* additional context information.
*
* @param method Service method being called.
* @param context Context information about the current service call.
* @return The updated context containing the span context.
*/
private Context startTracingSpan(Method method, Context context) {
boolean disableTracing = (boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false);
if (!TracerProxy.isTracingEnabled() || disableTracing) {
return context;
}
String spanName = String.format("%s.%s", interfaceParser.getServiceName(), method.getName());
context = TracerProxy.setSpanName(spanName, context);
return TracerProxy.start(spanName, context);
}
/**
* Create a HttpRequest for the provided Swagger method using the provided arguments.
*
* @param methodParser the Swagger method parser to use
* @param args the arguments to use to populate the method's annotation values
* @return a HttpRequest
* @throws IOException thrown if the body contents cannot be serialized
*/
@SuppressWarnings("unchecked")
private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser,
final Object[] args) throws IOException {
final Object bodyContentObject = methodParser.setBody(args);
if (bodyContentObject == null) {
request.getHeaders().set("Content-Length", "0");
} else {
String contentType = methodParser.getBodyContentType();
if (contentType == null || contentType.isEmpty()) {
if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) {
contentType = ContentType.APPLICATION_OCTET_STREAM;
} else {
contentType = ContentType.APPLICATION_JSON;
}
}
request.getHeaders().set("Content-Type", contentType);
boolean isJson = false;
final String[] contentTypeParts = contentType.split(";");
for (final String contentTypePart : contentTypeParts) {
if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) {
isJson = true;
break;
}
}
if (isJson) {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size()))));
} else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) {
request.setBody((Flux<ByteBuffer>) bodyContentObject);
} else if (bodyContentObject instanceof byte[]) {
request.setBody((byte[]) bodyContentObject);
} else if (bodyContentObject instanceof String) {
final String bodyContentString = (String) bodyContentObject;
if (!bodyContentString.isEmpty()) {
request.setBody(bodyContentString);
}
} else if (bodyContentObject instanceof ByteBuffer) {
request.setBody(Flux.just((ByteBuffer) bodyContentObject));
} else {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size()))));
}
}
return request;
}
private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse,
final SwaggerMethodParser methodParser) {
return asyncDecodedResponse
.flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser));
}
private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception,
final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) {
final int responseStatusCode = httpResponse.getStatusCode();
final String contentType = httpResponse.getHeaderValue("Content-Type");
final String bodyRepresentation;
if ("application/octet-stream".equalsIgnoreCase(contentType)) {
bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)";
} else {
bodyRepresentation = responseContent == null || responseContent.length == 0
? "(empty body)"
: "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\"";
}
Exception result;
try {
final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType()
.getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType());
result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation,
httpResponse, responseDecodedContent);
} catch (ReflectiveOperationException e) {
String message = "Status code " + responseStatusCode + ", but an instance of "
+ exception.getExceptionType().getCanonicalName() + " cannot be created."
+ " Response body: " + bodyRepresentation;
result = new IOException(message, e);
}
return result;
}
/**
* Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status
* code' OR (2) emits provided response if it's status code ia allowed.
*
* 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[]
* of additional allowed status codes.
*
* @param decodedResponse The HttpResponse to check.
* @param methodParser The method parser that contains information about the service interface method that initiated
* the HTTP request.
* @return An async-version of the provided decodedResponse.
*/
private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse,
final SwaggerMethodParser methodParser) {
final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode();
final Mono<HttpDecodedResponse> asyncResult;
if (!methodParser.isExpectedResponseStatusCode(responseStatusCode)) {
Mono<byte[]> bodyAsBytes = decodedResponse.getSourceResponse().getBodyAsByteArray();
asyncResult = bodyAsBytes.flatMap((Function<byte[], Mono<HttpDecodedResponse>>) responseContent -> {
Mono<Object> decodedErrorBody = decodedResponse.getDecodedBody(responseContent);
return decodedErrorBody
.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> {
Throwable exception = instantiateUnexpectedException(
methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseContent, responseDecodedErrorObject);
return Mono.error(exception);
})
.switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> {
Throwable exception = instantiateUnexpectedException(
methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseContent, null);
return Mono.error(exception);
}));
}).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> {
Throwable exception =
instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), null, null);
return Mono.error(exception);
}));
} else {
asyncResult = Mono.just(decodedResponse);
}
return asyncResult;
}
private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser,
final Type entityType) {
if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) {
final Type bodyType = TypeUtil.getRestResponseBodyType(entityType);
if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) {
return response.getSourceResponse().getBody().ignoreElements()
.then(createResponse(response, entityType, null));
} else {
return handleBodyReturnType(response, methodParser, bodyType)
.flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject))
.switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response,
entityType, null)));
}
} else {
return handleBodyReturnType(response, methodParser, entityType);
}
}
@SuppressWarnings("unchecked")
private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) {
Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType);
if (cls.equals(Response.class)) {
cls = (Class<? extends Response<?>>) (Object) ResponseBase.class;
} else if (cls.equals(PagedResponse.class)) {
cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class;
if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) {
return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR));
}
}
return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(cls))
.switchIfEmpty(Mono.error(new RuntimeException("Cannot find suitable constructor for class " + cls)))
.flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject));
}
private Mono<?> handleBodyReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Mono<?> asyncResult;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(
entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
asyncResult = Mono.just(isSuccess);
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray();
if (returnValueWireType == Base64Url.class) {
responseBodyBytesAsync =
responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes());
}
asyncResult = responseBodyBytesAsync;
} else if (FluxUtil.isFluxByteBuffer(entityType)) {
asyncResult = Mono.just(response.getSourceResponse().getBody());
} else {
asyncResult = response.getDecodedBody((byte[]) null);
}
return asyncResult;
}
/**
* Handle the provided asynchronous HTTP response and return the deserialized value.
*
* @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request
* @param methodParser the SwaggerMethodParser that the request originates from
* @param returnType the type of value that will be returned
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return the deserialized result
*/
private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse,
final SwaggerMethodParser methodParser,
final Type returnType,
final Context context) {
final Mono<HttpDecodedResponse> asyncExpectedResponse =
ensureExpectedStatus(asyncHttpDecodedResponse, methodParser)
.doOnEach(RestProxy::endTracingSpan)
.contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context));
final Object result;
if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) {
final Type monoTypeParam = TypeUtil.getTypeArgument(returnType);
if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) {
result = asyncExpectedResponse.then();
} else {
result = asyncExpectedResponse.flatMap(response ->
handleRestResponseReturnType(response, methodParser, monoTypeParam));
}
} else if (FluxUtil.isFluxByteBuffer(returnType)) {
result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody());
} else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType,
Void.class)) {
asyncExpectedResponse.block();
result = null;
} else {
result = asyncExpectedResponse
.flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType))
.block();
}
return result;
}
private static void endTracingSpan(Signal<HttpDecodedResponse> signal) {
if (!TracerProxy.isTracingEnabled()) {
return;
}
if (signal.isOnComplete() || signal.isOnSubscribe()) {
return;
}
ContextView context = signal.getContextView();
Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT");
boolean disableTracing = context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false);
if (!tracingContext.isPresent() || disableTracing) {
return;
}
int statusCode = 0;
HttpDecodedResponse httpDecodedResponse;
Throwable throwable = null;
if (signal.hasValue()) {
httpDecodedResponse = signal.get();
statusCode = httpDecodedResponse.getSourceResponse().getStatusCode();
} else if (signal.hasError()) {
throwable = signal.getThrowable();
if (throwable instanceof HttpResponseException) {
HttpResponseException exception = (HttpResponseException) throwable;
statusCode = exception.getResponse().getStatusCode();
}
}
TracerProxy.end(statusCode, throwable, tracingContext.get());
}
/**
* Create an instance of the default serializer.
*
* @return the default serializer
*/
private static SerializerAdapter createDefaultSerializer() {
return JacksonAdapter.createDefaultSerializerAdapter();
}
/**
* Create the default HttpPipeline.
*
* @return the default HttpPipeline
*/
private static HttpPipeline createDefaultPipeline() {
return createDefaultPipeline(null);
}
/**
* Create the default HttpPipeline.
*
* @param credentialsPolicy the credentials policy factory to use to apply authentication to the pipeline
* @return the default HttpPipeline
*/
private static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy());
policies.add(new RetryPolicy());
policies.add(new CookiePolicy());
if (credentialsPolicy != null) {
policies.add(credentialsPolicy);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param <A> the type of the Swagger interface
* @return a proxy implementation of the provided Swagger interface
*/
public static <A> A create(Class<A> swaggerInterface) {
return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer());
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests
* @param <A> the type of the Swagger interface
* @return a proxy implementation of the provided Swagger interface
*/
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) {
return create(swaggerInterface, httpPipeline, createDefaultSerializer());
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests
* @param serializer the serializer that will be used to convert POJOs to and from request and response bodies
* @param <A> the type of the Swagger interface.
* @return a proxy implementation of the provided Swagger interface
*/
@SuppressWarnings("unchecked")
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) {
final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer);
final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser);
return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface},
restProxy);
}
} |
Any reason to change the resource prefix to CRC32 instead of using the test name as previously was being done | public StorageResourceNamer(String testName, TestMode testMode, RecordedData recordedData) {
Objects.requireNonNull(testName);
Objects.requireNonNull(testMode);
Objects.requireNonNull(recordedData);
resourcePrefix = getCrc32(testName);
testResourceNamer = new TestResourceNamer(resourcePrefix, testMode, recordedData);
} | resourcePrefix = getCrc32(testName); | public StorageResourceNamer(String testName, TestMode testMode, RecordedData recordedData) {
Objects.requireNonNull(testName);
Objects.requireNonNull(testMode);
resourcePrefix = getCrc32(testName);
testResourceNamer = new TestResourceNamer(resourcePrefix, testMode, recordedData);
} | class StorageResourceNamer {
private final TestResourceNamer testResourceNamer;
private final String resourcePrefix;
public String getResourcePrefix() {
return resourcePrefix;
}
public String getRandomName(int maxLength) {
return testResourceNamer.randomName(getResourcePrefix(), maxLength);
}
public String getRandomName(String prefix, int maxLength) {
Objects.requireNonNull(prefix);
return testResourceNamer.randomName(prefix, maxLength);
}
public OffsetDateTime getUtcNow() {
return testResourceNamer.now();
}
public String getRandomUuid() {
return testResourceNamer.randomUuid();
}
private static String getCrc32(String input) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(StandardCharsets.UTF_8));
return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase();
}
} | class StorageResourceNamer {
private final TestResourceNamer testResourceNamer;
private final String resourcePrefix;
public String getResourcePrefix() {
return resourcePrefix;
}
public String getRandomName(int maxLength) {
return testResourceNamer.randomName(getResourcePrefix(), maxLength);
}
public String getRandomName(String prefix, int maxLength) {
Objects.requireNonNull(prefix);
return testResourceNamer.randomName(prefix, maxLength);
}
public OffsetDateTime getUtcNow() {
return testResourceNamer.now();
}
public String getRandomUuid() {
return testResourceNamer.randomUuid();
}
private static String getCrc32(String input) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(StandardCharsets.UTF_8));
return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase();
}
} |
"test bla" and "test bla fail" collide at cleanup. If run in parallel this creates race conditions. I was experimenting with just uuid, but this one is shorter (we'll revisit that choice if collisions are problematic, but I don't recall this being a problem in python where they crc32) | public StorageResourceNamer(String testName, TestMode testMode, RecordedData recordedData) {
Objects.requireNonNull(testName);
Objects.requireNonNull(testMode);
Objects.requireNonNull(recordedData);
resourcePrefix = getCrc32(testName);
testResourceNamer = new TestResourceNamer(resourcePrefix, testMode, recordedData);
} | resourcePrefix = getCrc32(testName); | public StorageResourceNamer(String testName, TestMode testMode, RecordedData recordedData) {
Objects.requireNonNull(testName);
Objects.requireNonNull(testMode);
resourcePrefix = getCrc32(testName);
testResourceNamer = new TestResourceNamer(resourcePrefix, testMode, recordedData);
} | class StorageResourceNamer {
private final TestResourceNamer testResourceNamer;
private final String resourcePrefix;
public String getResourcePrefix() {
return resourcePrefix;
}
public String getRandomName(int maxLength) {
return testResourceNamer.randomName(getResourcePrefix(), maxLength);
}
public String getRandomName(String prefix, int maxLength) {
Objects.requireNonNull(prefix);
return testResourceNamer.randomName(prefix, maxLength);
}
public OffsetDateTime getUtcNow() {
return testResourceNamer.now();
}
public String getRandomUuid() {
return testResourceNamer.randomUuid();
}
private static String getCrc32(String input) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(StandardCharsets.UTF_8));
return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase();
}
} | class StorageResourceNamer {
private final TestResourceNamer testResourceNamer;
private final String resourcePrefix;
public String getResourcePrefix() {
return resourcePrefix;
}
public String getRandomName(int maxLength) {
return testResourceNamer.randomName(getResourcePrefix(), maxLength);
}
public String getRandomName(String prefix, int maxLength) {
Objects.requireNonNull(prefix);
return testResourceNamer.randomName(prefix, maxLength);
}
public OffsetDateTime getUtcNow() {
return testResourceNamer.now();
}
public String getRandomUuid() {
return testResourceNamer.randomUuid();
}
private static String getCrc32(String input) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(StandardCharsets.UTF_8));
return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase();
}
} |
I've seen plenty of that when running blobs in parallel. Which yielded this workaround https://github.com/Azure/azure-sdk-for-java/blob/9ee4c8904e6f1d3f9c3fafd51bc6ae3a4b4d40a2/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/APISpec.groovy#L172-L176 This should enable parallelization in all modes. | public StorageResourceNamer(String testName, TestMode testMode, RecordedData recordedData) {
Objects.requireNonNull(testName);
Objects.requireNonNull(testMode);
Objects.requireNonNull(recordedData);
resourcePrefix = getCrc32(testName);
testResourceNamer = new TestResourceNamer(resourcePrefix, testMode, recordedData);
} | resourcePrefix = getCrc32(testName); | public StorageResourceNamer(String testName, TestMode testMode, RecordedData recordedData) {
Objects.requireNonNull(testName);
Objects.requireNonNull(testMode);
resourcePrefix = getCrc32(testName);
testResourceNamer = new TestResourceNamer(resourcePrefix, testMode, recordedData);
} | class StorageResourceNamer {
private final TestResourceNamer testResourceNamer;
private final String resourcePrefix;
public String getResourcePrefix() {
return resourcePrefix;
}
public String getRandomName(int maxLength) {
return testResourceNamer.randomName(getResourcePrefix(), maxLength);
}
public String getRandomName(String prefix, int maxLength) {
Objects.requireNonNull(prefix);
return testResourceNamer.randomName(prefix, maxLength);
}
public OffsetDateTime getUtcNow() {
return testResourceNamer.now();
}
public String getRandomUuid() {
return testResourceNamer.randomUuid();
}
private static String getCrc32(String input) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(StandardCharsets.UTF_8));
return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase();
}
} | class StorageResourceNamer {
private final TestResourceNamer testResourceNamer;
private final String resourcePrefix;
public String getResourcePrefix() {
return resourcePrefix;
}
public String getRandomName(int maxLength) {
return testResourceNamer.randomName(getResourcePrefix(), maxLength);
}
public String getRandomName(String prefix, int maxLength) {
Objects.requireNonNull(prefix);
return testResourceNamer.randomName(prefix, maxLength);
}
public OffsetDateTime getUtcNow() {
return testResourceNamer.now();
}
public String getRandomUuid() {
return testResourceNamer.randomUuid();
}
private static String getCrc32(String input) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(StandardCharsets.UTF_8));
return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase();
}
} |
Can we check the test status and always log if the test failed? The junit errors may not always give all the details. | public void afterTestExecution(ExtensionContext context) {
if (!SHOULD_LOG_EXECUTION_STATUS.get()) {
return;
}
TestRunMetrics testInformation = getStore(context)
.remove(context.getRequiredTestMethod(), TestRunMetrics.class);
long duration = System.currentTimeMillis() - testInformation.getStartMillis();
System.out.printf("%s completed in %d ms.%n", testInformation.getLogPrefix(), duration);
} | } | public void afterTestExecution(ExtensionContext context) {
if (!SHOULD_LOG_EXECUTION_STATUS.get()) {
return;
}
TestRunMetrics testInformation = getStore(context)
.remove(context.getRequiredTestMethod(), TestRunMetrics.class);
long duration = System.currentTimeMillis() - testInformation.getStartMillis();
System.out.printf("%s completed in %d ms.%n", testInformation.getLogPrefix(), duration);
} | class AzureTestWatcher implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
private static final String AZURE_TEST_DEBUG = "AZURE_TEST_DEBUG";
private static final Supplier<Boolean> SHOULD_LOG_EXECUTION_STATUS = () ->
Boolean.parseBoolean(Configuration.getGlobalConfiguration().get(AZURE_TEST_DEBUG));
@Override
public void beforeTestExecution(ExtensionContext extensionContext) {
if (!SHOULD_LOG_EXECUTION_STATUS.get()) {
return;
}
String displayName = extensionContext.getDisplayName();
String testName = "";
String fullyQualifiedTestName = "";
if (extensionContext.getTestMethod().isPresent()) {
Method method = extensionContext.getTestMethod().get();
testName = method.getName();
fullyQualifiedTestName = method.getDeclaringClass().getName() + "." + testName;
}
StringBuilder logPrefixBuilder = new StringBuilder("Starting test ")
.append(fullyQualifiedTestName);
if (!Objects.equals(displayName, testName)) {
logPrefixBuilder.append("(")
.append(displayName)
.append(")");
}
logPrefixBuilder.append(",");
getStore(extensionContext).put(extensionContext.getRequiredTestMethod(),
new TestRunMetrics(logPrefixBuilder.toString(), System.currentTimeMillis()));
}
@Override
private static ExtensionContext.Store getStore(ExtensionContext context) {
return context.getStore(ExtensionContext.Namespace.create(AzureTestWatcher.class, context));
}
} | class AzureTestWatcher implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
private static final String AZURE_TEST_DEBUG = "AZURE_TEST_DEBUG";
private static final Supplier<Boolean> SHOULD_LOG_EXECUTION_STATUS = () ->
Boolean.parseBoolean(Configuration.getGlobalConfiguration().get(AZURE_TEST_DEBUG));
@Override
public void beforeTestExecution(ExtensionContext extensionContext) {
if (!SHOULD_LOG_EXECUTION_STATUS.get()) {
return;
}
String displayName = extensionContext.getDisplayName();
String testName = "";
String fullyQualifiedTestName = "";
if (extensionContext.getTestMethod().isPresent()) {
Method method = extensionContext.getTestMethod().get();
testName = method.getName();
fullyQualifiedTestName = method.getDeclaringClass().getName() + "." + testName;
}
StringBuilder logPrefixBuilder = new StringBuilder("Starting test ")
.append(fullyQualifiedTestName);
if (!Objects.equals(displayName, testName)) {
logPrefixBuilder.append("(")
.append(displayName)
.append(")");
}
logPrefixBuilder.append(",");
getStore(extensionContext).put(extensionContext.getRequiredTestMethod(),
new TestRunMetrics(logPrefixBuilder.toString(), System.currentTimeMillis()));
}
@Override
private static ExtensionContext.Store getStore(ExtensionContext context) {
return context.getStore(ExtensionContext.Namespace.create(AzureTestWatcher.class, context));
}
} |
This is that PR 😃 | private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException {
final String path = methodParser.setPath(args);
final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path);
final UrlBuilder urlBuilder;
if (pathUrlBuilder.getScheme() != null) {
urlBuilder = pathUrlBuilder;
} else {
urlBuilder = new UrlBuilder();
methodParser.setSchemeAndHost(args, urlBuilder);
if (path != null && !path.isEmpty() && !"/".equals(path)) {
String hostPath = urlBuilder.getPath();
if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(":
urlBuilder.setPath(path);
} else {
if (path.startsWith("/")) {
urlBuilder.setPath(hostPath + path);
} else {
urlBuilder.setPath(hostPath + "/" + path);
}
}
}
}
methodParser.setEncodedQueryParameters(args, urlBuilder);
final URL url = urlBuilder.toUrl();
final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url),
methodParser, args);
HttpHeaders httpHeaders = request.getHeaders();
methodParser.setHeaders(args, httpHeaders);
return request;
} | } | private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException {
final String path = methodParser.setPath(args);
final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path);
final UrlBuilder urlBuilder;
if (pathUrlBuilder.getScheme() != null) {
urlBuilder = pathUrlBuilder;
} else {
urlBuilder = new UrlBuilder();
methodParser.setSchemeAndHost(args, urlBuilder);
if (path != null && !path.isEmpty() && !"/".equals(path)) {
String hostPath = urlBuilder.getPath();
if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(":
urlBuilder.setPath(path);
} else {
if (path.startsWith("/")) {
urlBuilder.setPath(hostPath + path);
} else {
urlBuilder.setPath(hostPath + "/" + path);
}
}
}
}
methodParser.setEncodedQueryParameters(args, urlBuilder);
final URL url = urlBuilder.toUrl();
final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url),
methodParser, args);
HttpHeaders httpHeaders = request.getHeaders();
methodParser.setHeaders(args, httpHeaders);
return request;
} | class RestProxy implements InvocationHandler {
private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0);
private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes.";
private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes.";
private static final String MUST_IMPLEMENT_PAGE_ERROR =
"Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class;
private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache();
private final ClientLogger logger = new ClientLogger(RestProxy.class);
private final HttpPipeline httpPipeline;
private final SerializerAdapter serializer;
private final SwaggerInterfaceParser interfaceParser;
private final HttpResponseDecoder decoder;
/**
* Create a RestProxy.
*
* @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests.
* @param serializer the serializer that will be used to convert response bodies to POJOs.
* @param interfaceParser the parser that contains information about the interface describing REST API methods that
* this RestProxy "implements".
*/
private RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) {
this.httpPipeline = httpPipeline;
this.serializer = serializer;
this.interfaceParser = interfaceParser;
this.decoder = new HttpResponseDecoder(this.serializer);
}
/**
* Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this
* RestProxy was created to "implement".
*
* @param method the method to get a SwaggerMethodParser for
* @return the SwaggerMethodParser for the provided method
*/
private SwaggerMethodParser getMethodParser(Method method) {
return interfaceParser.getMethodParser(method);
}
/**
* Send the provided request asynchronously, applying any request policies provided to the HttpClient instance.
*
* @param request the HTTP request to send
* @param contextData the context
* @return a {@link Mono} that emits HttpResponse asynchronously
*/
public Mono<HttpResponse> send(HttpRequest request, Context contextData) {
return httpPipeline.send(request, contextData);
}
@Override
public Object invoke(Object proxy, final Method method, Object[] args) {
try {
if (method.isAnnotationPresent(ResumeOperation.class)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new Exception("The resume operation isn't supported.")));
}
final SwaggerMethodParser methodParser = getMethodParser(method);
final HttpRequest request = createHttpRequest(methodParser, args);
Context context = methodParser.setContext(args)
.addData("caller-method", methodParser.getFullyQualifiedMethodName())
.addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType()));
context = startTracingSpan(method, context);
if (request.getBody() != null) {
request.setBody(validateLength(request));
}
final Mono<HttpResponse> asyncResponse = send(request, context);
Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser);
return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context);
} catch (IOException e) {
throw logger.logExceptionAsError(Exceptions.propagate(e));
}
}
static Flux<ByteBuffer> validateLength(final HttpRequest request) {
final Flux<ByteBuffer> bbFlux = request.getBody();
if (bbFlux == null) {
return Flux.empty();
}
final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length"));
return Flux.defer(() -> {
final long[] currentTotalLength = new long[1];
return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> {
if (buffer == null) {
return;
}
if (buffer == VALIDATION_BUFFER) {
if (expectedLength != currentTotalLength[0]) {
sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL,
currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength));
} else {
sink.complete();
}
return;
}
currentTotalLength[0] += buffer.remaining();
if (currentTotalLength[0] > expectedLength) {
sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE,
currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength));
return;
}
sink.next(buffer);
});
});
}
/**
* Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing
* additional context information.
*
* @param method Service method being called.
* @param context Context information about the current service call.
* @return The updated context containing the span context.
*/
private Context startTracingSpan(Method method, Context context) {
boolean disableTracing = (boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false);
if (!TracerProxy.isTracingEnabled() || disableTracing) {
return context;
}
String spanName = String.format("%s.%s", interfaceParser.getServiceName(), method.getName());
context = TracerProxy.setSpanName(spanName, context);
return TracerProxy.start(spanName, context);
}
/**
* Create a HttpRequest for the provided Swagger method using the provided arguments.
*
* @param methodParser the Swagger method parser to use
* @param args the arguments to use to populate the method's annotation values
* @return a HttpRequest
* @throws IOException thrown if the body contents cannot be serialized
*/
@SuppressWarnings("unchecked")
private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser,
final Object[] args) throws IOException {
final Object bodyContentObject = methodParser.setBody(args);
if (bodyContentObject == null) {
request.getHeaders().set("Content-Length", "0");
} else {
String contentType = methodParser.getBodyContentType();
if (contentType == null || contentType.isEmpty()) {
if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) {
contentType = ContentType.APPLICATION_OCTET_STREAM;
} else {
contentType = ContentType.APPLICATION_JSON;
}
}
request.getHeaders().set("Content-Type", contentType);
boolean isJson = false;
final String[] contentTypeParts = contentType.split(";");
for (final String contentTypePart : contentTypeParts) {
if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) {
isJson = true;
break;
}
}
if (isJson) {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size()))));
} else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) {
request.setBody((Flux<ByteBuffer>) bodyContentObject);
} else if (bodyContentObject instanceof byte[]) {
request.setBody((byte[]) bodyContentObject);
} else if (bodyContentObject instanceof String) {
final String bodyContentString = (String) bodyContentObject;
if (!bodyContentString.isEmpty()) {
request.setBody(bodyContentString);
}
} else if (bodyContentObject instanceof ByteBuffer) {
request.setBody(Flux.just((ByteBuffer) bodyContentObject));
} else {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size()))));
}
}
return request;
}
private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse,
final SwaggerMethodParser methodParser) {
return asyncDecodedResponse
.flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser));
}
private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception,
final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) {
final int responseStatusCode = httpResponse.getStatusCode();
final String contentType = httpResponse.getHeaderValue("Content-Type");
final String bodyRepresentation;
if ("application/octet-stream".equalsIgnoreCase(contentType)) {
bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)";
} else {
bodyRepresentation = responseContent == null || responseContent.length == 0
? "(empty body)"
: "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\"";
}
Exception result;
try {
final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType()
.getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType());
result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation,
httpResponse, responseDecodedContent);
} catch (ReflectiveOperationException e) {
String message = "Status code " + responseStatusCode + ", but an instance of "
+ exception.getExceptionType().getCanonicalName() + " cannot be created."
+ " Response body: " + bodyRepresentation;
result = new IOException(message, e);
}
return result;
}
/**
* Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status
* code' OR (2) emits provided response if it's status code ia allowed.
*
* 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[]
* of additional allowed status codes.
*
* @param decodedResponse The HttpResponse to check.
* @param methodParser The method parser that contains information about the service interface method that initiated
* the HTTP request.
* @return An async-version of the provided decodedResponse.
*/
private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse,
final SwaggerMethodParser methodParser) {
final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode();
final Mono<HttpDecodedResponse> asyncResult;
if (!methodParser.isExpectedResponseStatusCode(responseStatusCode)) {
Mono<byte[]> bodyAsBytes = decodedResponse.getSourceResponse().getBodyAsByteArray();
asyncResult = bodyAsBytes.flatMap((Function<byte[], Mono<HttpDecodedResponse>>) responseContent -> {
Mono<Object> decodedErrorBody = decodedResponse.getDecodedBody(responseContent);
return decodedErrorBody
.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> {
Throwable exception = instantiateUnexpectedException(
methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseContent, responseDecodedErrorObject);
return Mono.error(exception);
})
.switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> {
Throwable exception = instantiateUnexpectedException(
methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseContent, null);
return Mono.error(exception);
}));
}).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> {
Throwable exception =
instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), null, null);
return Mono.error(exception);
}));
} else {
asyncResult = Mono.just(decodedResponse);
}
return asyncResult;
}
private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser,
final Type entityType) {
if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) {
final Type bodyType = TypeUtil.getRestResponseBodyType(entityType);
if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) {
return response.getSourceResponse().getBody().ignoreElements()
.then(createResponse(response, entityType, null));
} else {
return handleBodyReturnType(response, methodParser, bodyType)
.flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject))
.switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response,
entityType, null)));
}
} else {
return handleBodyReturnType(response, methodParser, entityType);
}
}
@SuppressWarnings("unchecked")
private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) {
Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType);
if (cls.equals(Response.class)) {
cls = (Class<? extends Response<?>>) (Object) ResponseBase.class;
} else if (cls.equals(PagedResponse.class)) {
cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class;
if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) {
return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR));
}
}
return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(cls))
.switchIfEmpty(Mono.error(new RuntimeException("Cannot find suitable constructor for class " + cls)))
.flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject));
}
private Mono<?> handleBodyReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Mono<?> asyncResult;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(
entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
asyncResult = Mono.just(isSuccess);
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray();
if (returnValueWireType == Base64Url.class) {
responseBodyBytesAsync =
responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes());
}
asyncResult = responseBodyBytesAsync;
} else if (FluxUtil.isFluxByteBuffer(entityType)) {
asyncResult = Mono.just(response.getSourceResponse().getBody());
} else {
asyncResult = response.getDecodedBody((byte[]) null);
}
return asyncResult;
}
/**
* Handle the provided asynchronous HTTP response and return the deserialized value.
*
* @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request
* @param methodParser the SwaggerMethodParser that the request originates from
* @param returnType the type of value that will be returned
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return the deserialized result
*/
private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse,
final SwaggerMethodParser methodParser,
final Type returnType,
final Context context) {
final Mono<HttpDecodedResponse> asyncExpectedResponse =
ensureExpectedStatus(asyncHttpDecodedResponse, methodParser)
.doOnEach(RestProxy::endTracingSpan)
.contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context));
final Object result;
if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) {
final Type monoTypeParam = TypeUtil.getTypeArgument(returnType);
if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) {
result = asyncExpectedResponse.then();
} else {
result = asyncExpectedResponse.flatMap(response ->
handleRestResponseReturnType(response, methodParser, monoTypeParam));
}
} else if (FluxUtil.isFluxByteBuffer(returnType)) {
result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody());
} else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType,
Void.class)) {
asyncExpectedResponse.block();
result = null;
} else {
result = asyncExpectedResponse
.flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType))
.block();
}
return result;
}
private static void endTracingSpan(Signal<HttpDecodedResponse> signal) {
if (!TracerProxy.isTracingEnabled()) {
return;
}
if (signal.isOnComplete() || signal.isOnSubscribe()) {
return;
}
ContextView context = signal.getContextView();
Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT");
boolean disableTracing = context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false);
if (!tracingContext.isPresent() || disableTracing) {
return;
}
int statusCode = 0;
HttpDecodedResponse httpDecodedResponse;
Throwable throwable = null;
if (signal.hasValue()) {
httpDecodedResponse = signal.get();
statusCode = httpDecodedResponse.getSourceResponse().getStatusCode();
} else if (signal.hasError()) {
throwable = signal.getThrowable();
if (throwable instanceof HttpResponseException) {
HttpResponseException exception = (HttpResponseException) throwable;
statusCode = exception.getResponse().getStatusCode();
}
}
TracerProxy.end(statusCode, throwable, tracingContext.get());
}
/**
* Create an instance of the default serializer.
*
* @return the default serializer
*/
private static SerializerAdapter createDefaultSerializer() {
return JacksonAdapter.createDefaultSerializerAdapter();
}
/**
* Create the default HttpPipeline.
*
* @return the default HttpPipeline
*/
private static HttpPipeline createDefaultPipeline() {
return createDefaultPipeline(null);
}
/**
* Create the default HttpPipeline.
*
* @param credentialsPolicy the credentials policy factory to use to apply authentication to the pipeline
* @return the default HttpPipeline
*/
private static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy());
policies.add(new RetryPolicy());
policies.add(new CookiePolicy());
if (credentialsPolicy != null) {
policies.add(credentialsPolicy);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param <A> the type of the Swagger interface
* @return a proxy implementation of the provided Swagger interface
*/
public static <A> A create(Class<A> swaggerInterface) {
return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer());
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests
* @param <A> the type of the Swagger interface
* @return a proxy implementation of the provided Swagger interface
*/
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) {
return create(swaggerInterface, httpPipeline, createDefaultSerializer());
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests
* @param serializer the serializer that will be used to convert POJOs to and from request and response bodies
* @param <A> the type of the Swagger interface.
* @return a proxy implementation of the provided Swagger interface
*/
@SuppressWarnings("unchecked")
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) {
final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer);
final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser);
return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface},
restProxy);
}
} | class RestProxy implements InvocationHandler {
private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0);
private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes.";
private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes.";
private static final String MUST_IMPLEMENT_PAGE_ERROR =
"Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class;
private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache();
private final ClientLogger logger = new ClientLogger(RestProxy.class);
private final HttpPipeline httpPipeline;
private final SerializerAdapter serializer;
private final SwaggerInterfaceParser interfaceParser;
private final HttpResponseDecoder decoder;
/**
* Create a RestProxy.
*
* @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests.
* @param serializer the serializer that will be used to convert response bodies to POJOs.
* @param interfaceParser the parser that contains information about the interface describing REST API methods that
* this RestProxy "implements".
*/
private RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) {
this.httpPipeline = httpPipeline;
this.serializer = serializer;
this.interfaceParser = interfaceParser;
this.decoder = new HttpResponseDecoder(this.serializer);
}
/**
* Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this
* RestProxy was created to "implement".
*
* @param method the method to get a SwaggerMethodParser for
* @return the SwaggerMethodParser for the provided method
*/
private SwaggerMethodParser getMethodParser(Method method) {
return interfaceParser.getMethodParser(method);
}
/**
* Send the provided request asynchronously, applying any request policies provided to the HttpClient instance.
*
* @param request the HTTP request to send
* @param contextData the context
* @return a {@link Mono} that emits HttpResponse asynchronously
*/
public Mono<HttpResponse> send(HttpRequest request, Context contextData) {
return httpPipeline.send(request, contextData);
}
@Override
public Object invoke(Object proxy, final Method method, Object[] args) {
try {
if (method.isAnnotationPresent(ResumeOperation.class)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new Exception("The resume operation isn't supported.")));
}
final SwaggerMethodParser methodParser = getMethodParser(method);
final HttpRequest request = createHttpRequest(methodParser, args);
Context context = methodParser.setContext(args)
.addData("caller-method", methodParser.getFullyQualifiedMethodName())
.addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType()));
context = startTracingSpan(method, context);
if (request.getBody() != null) {
request.setBody(validateLength(request));
}
final Mono<HttpResponse> asyncResponse = send(request, context);
Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser);
return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context);
} catch (IOException e) {
throw logger.logExceptionAsError(Exceptions.propagate(e));
}
}
static Flux<ByteBuffer> validateLength(final HttpRequest request) {
final Flux<ByteBuffer> bbFlux = request.getBody();
if (bbFlux == null) {
return Flux.empty();
}
final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length"));
return Flux.defer(() -> {
final long[] currentTotalLength = new long[1];
return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> {
if (buffer == null) {
return;
}
if (buffer == VALIDATION_BUFFER) {
if (expectedLength != currentTotalLength[0]) {
sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL,
currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength));
} else {
sink.complete();
}
return;
}
currentTotalLength[0] += buffer.remaining();
if (currentTotalLength[0] > expectedLength) {
sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE,
currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength));
return;
}
sink.next(buffer);
});
});
}
/**
* Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing
* additional context information.
*
* @param method Service method being called.
* @param context Context information about the current service call.
* @return The updated context containing the span context.
*/
private Context startTracingSpan(Method method, Context context) {
boolean disableTracing = (boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false);
if (!TracerProxy.isTracingEnabled() || disableTracing) {
return context;
}
String spanName = String.format("%s.%s", interfaceParser.getServiceName(), method.getName());
context = TracerProxy.setSpanName(spanName, context);
return TracerProxy.start(spanName, context);
}
/**
* Create a HttpRequest for the provided Swagger method using the provided arguments.
*
* @param methodParser the Swagger method parser to use
* @param args the arguments to use to populate the method's annotation values
* @return a HttpRequest
* @throws IOException thrown if the body contents cannot be serialized
*/
@SuppressWarnings("unchecked")
private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser,
final Object[] args) throws IOException {
final Object bodyContentObject = methodParser.setBody(args);
if (bodyContentObject == null) {
request.getHeaders().set("Content-Length", "0");
} else {
String contentType = methodParser.getBodyContentType();
if (contentType == null || contentType.isEmpty()) {
if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) {
contentType = ContentType.APPLICATION_OCTET_STREAM;
} else {
contentType = ContentType.APPLICATION_JSON;
}
}
request.getHeaders().set("Content-Type", contentType);
boolean isJson = false;
final String[] contentTypeParts = contentType.split(";");
for (final String contentTypePart : contentTypeParts) {
if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) {
isJson = true;
break;
}
}
if (isJson) {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size()))));
} else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) {
request.setBody((Flux<ByteBuffer>) bodyContentObject);
} else if (bodyContentObject instanceof byte[]) {
request.setBody((byte[]) bodyContentObject);
} else if (bodyContentObject instanceof String) {
final String bodyContentString = (String) bodyContentObject;
if (!bodyContentString.isEmpty()) {
request.setBody(bodyContentString);
}
} else if (bodyContentObject instanceof ByteBuffer) {
request.setBody(Flux.just((ByteBuffer) bodyContentObject));
} else {
ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream();
serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream);
request.setHeader("Content-Length", String.valueOf(stream.size()));
request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size()))));
}
}
return request;
}
private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse,
final SwaggerMethodParser methodParser) {
return asyncDecodedResponse
.flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser));
}
private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception,
final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) {
final int responseStatusCode = httpResponse.getStatusCode();
final String contentType = httpResponse.getHeaderValue("Content-Type");
final String bodyRepresentation;
if ("application/octet-stream".equalsIgnoreCase(contentType)) {
bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)";
} else {
bodyRepresentation = responseContent == null || responseContent.length == 0
? "(empty body)"
: "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\"";
}
Exception result;
try {
final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType()
.getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType());
result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation,
httpResponse, responseDecodedContent);
} catch (ReflectiveOperationException e) {
String message = "Status code " + responseStatusCode + ", but an instance of "
+ exception.getExceptionType().getCanonicalName() + " cannot be created."
+ " Response body: " + bodyRepresentation;
result = new IOException(message, e);
}
return result;
}
/**
* Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status
* code' OR (2) emits provided response if it's status code ia allowed.
*
* 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[]
* of additional allowed status codes.
*
* @param decodedResponse The HttpResponse to check.
* @param methodParser The method parser that contains information about the service interface method that initiated
* the HTTP request.
* @return An async-version of the provided decodedResponse.
*/
private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse,
final SwaggerMethodParser methodParser) {
final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode();
final Mono<HttpDecodedResponse> asyncResult;
if (!methodParser.isExpectedResponseStatusCode(responseStatusCode)) {
Mono<byte[]> bodyAsBytes = decodedResponse.getSourceResponse().getBodyAsByteArray();
asyncResult = bodyAsBytes.flatMap((Function<byte[], Mono<HttpDecodedResponse>>) responseContent -> {
Mono<Object> decodedErrorBody = decodedResponse.getDecodedBody(responseContent);
return decodedErrorBody
.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> {
Throwable exception = instantiateUnexpectedException(
methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseContent, responseDecodedErrorObject);
return Mono.error(exception);
})
.switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> {
Throwable exception = instantiateUnexpectedException(
methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), responseContent, null);
return Mono.error(exception);
}));
}).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> {
Throwable exception =
instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode),
decodedResponse.getSourceResponse(), null, null);
return Mono.error(exception);
}));
} else {
asyncResult = Mono.just(decodedResponse);
}
return asyncResult;
}
private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser,
final Type entityType) {
if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) {
final Type bodyType = TypeUtil.getRestResponseBodyType(entityType);
if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) {
return response.getSourceResponse().getBody().ignoreElements()
.then(createResponse(response, entityType, null));
} else {
return handleBodyReturnType(response, methodParser, bodyType)
.flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject))
.switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response,
entityType, null)));
}
} else {
return handleBodyReturnType(response, methodParser, entityType);
}
}
@SuppressWarnings("unchecked")
private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) {
Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType);
if (cls.equals(Response.class)) {
cls = (Class<? extends Response<?>>) (Object) ResponseBase.class;
} else if (cls.equals(PagedResponse.class)) {
cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class;
if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) {
return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR));
}
}
return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(cls))
.switchIfEmpty(Mono.error(new RuntimeException("Cannot find suitable constructor for class " + cls)))
.flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject));
}
private Mono<?> handleBodyReturnType(final HttpDecodedResponse response,
final SwaggerMethodParser methodParser, final Type entityType) {
final int responseStatusCode = response.getSourceResponse().getStatusCode();
final HttpMethod httpMethod = methodParser.getHttpMethod();
final Type returnValueWireType = methodParser.getReturnValueWireType();
final Mono<?> asyncResult;
if (httpMethod == HttpMethod.HEAD
&& (TypeUtil.isTypeOrSubTypeOf(
entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) {
boolean isSuccess = (responseStatusCode / 100) == 2;
asyncResult = Mono.just(isSuccess);
} else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) {
Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray();
if (returnValueWireType == Base64Url.class) {
responseBodyBytesAsync =
responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes());
}
asyncResult = responseBodyBytesAsync;
} else if (FluxUtil.isFluxByteBuffer(entityType)) {
asyncResult = Mono.just(response.getSourceResponse().getBody());
} else {
asyncResult = response.getDecodedBody((byte[]) null);
}
return asyncResult;
}
/**
* Handle the provided asynchronous HTTP response and return the deserialized value.
*
* @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request
* @param methodParser the SwaggerMethodParser that the request originates from
* @param returnType the type of value that will be returned
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return the deserialized result
*/
private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse,
final SwaggerMethodParser methodParser,
final Type returnType,
final Context context) {
final Mono<HttpDecodedResponse> asyncExpectedResponse =
ensureExpectedStatus(asyncHttpDecodedResponse, methodParser)
.doOnEach(RestProxy::endTracingSpan)
.contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context));
final Object result;
if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) {
final Type monoTypeParam = TypeUtil.getTypeArgument(returnType);
if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) {
result = asyncExpectedResponse.then();
} else {
result = asyncExpectedResponse.flatMap(response ->
handleRestResponseReturnType(response, methodParser, monoTypeParam));
}
} else if (FluxUtil.isFluxByteBuffer(returnType)) {
result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody());
} else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType,
Void.class)) {
asyncExpectedResponse.block();
result = null;
} else {
result = asyncExpectedResponse
.flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType))
.block();
}
return result;
}
private static void endTracingSpan(Signal<HttpDecodedResponse> signal) {
if (!TracerProxy.isTracingEnabled()) {
return;
}
if (signal.isOnComplete() || signal.isOnSubscribe()) {
return;
}
ContextView context = signal.getContextView();
Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT");
boolean disableTracing = context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false);
if (!tracingContext.isPresent() || disableTracing) {
return;
}
int statusCode = 0;
HttpDecodedResponse httpDecodedResponse;
Throwable throwable = null;
if (signal.hasValue()) {
httpDecodedResponse = signal.get();
statusCode = httpDecodedResponse.getSourceResponse().getStatusCode();
} else if (signal.hasError()) {
throwable = signal.getThrowable();
if (throwable instanceof HttpResponseException) {
HttpResponseException exception = (HttpResponseException) throwable;
statusCode = exception.getResponse().getStatusCode();
}
}
TracerProxy.end(statusCode, throwable, tracingContext.get());
}
/**
* Create an instance of the default serializer.
*
* @return the default serializer
*/
private static SerializerAdapter createDefaultSerializer() {
return JacksonAdapter.createDefaultSerializerAdapter();
}
/**
* Create the default HttpPipeline.
*
* @return the default HttpPipeline
*/
private static HttpPipeline createDefaultPipeline() {
return createDefaultPipeline(null);
}
/**
* Create the default HttpPipeline.
*
* @param credentialsPolicy the credentials policy factory to use to apply authentication to the pipeline
* @return the default HttpPipeline
*/
private static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy());
policies.add(new RetryPolicy());
policies.add(new CookiePolicy());
if (credentialsPolicy != null) {
policies.add(credentialsPolicy);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param <A> the type of the Swagger interface
* @return a proxy implementation of the provided Swagger interface
*/
public static <A> A create(Class<A> swaggerInterface) {
return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer());
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests
* @param <A> the type of the Swagger interface
* @return a proxy implementation of the provided Swagger interface
*/
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) {
return create(swaggerInterface, httpPipeline, createDefaultSerializer());
}
/**
* Create a proxy implementation of the provided Swagger interface.
*
* @param swaggerInterface the Swagger interface to provide a proxy implementation for
* @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests
* @param serializer the serializer that will be used to convert POJOs to and from request and response bodies
* @param <A> the type of the Swagger interface.
* @return a proxy implementation of the provided Swagger interface
*/
@SuppressWarnings("unchecked")
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) {
final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer);
final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser);
return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface},
restProxy);
}
} |
I believe when `query` is null or empty this should continue clearing the query | public UrlBuilder setQuery(String query) {
if (query != null && !query.isEmpty()) {
with(query, UrlTokenizerState.QUERY);
}
return this;
} | if (query != null && !query.isEmpty()) { | public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, List<String>> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new ArrayList<String>(Arrays.asList(queryParameterEncodedValue)));
return this;
}
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
public UrlBuilder appendQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new ArrayList<String>(Arrays.asList(queryParameterEncodedValue));
}
value.add(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder clearQuery() {
if (query != null && !query.isEmpty()) {
query.clear();
}
return this;
}
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, List<String>> getQuery() {
return query;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, List<String>> entry : query.entrySet()) {
for (String queryValue : entry.getValue()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
appendQueryParameter(nameValue[0], nameValue[1]);
} else {
appendQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 10000;
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, QueryParameter> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new QueryParameter(queryParameterName, queryParameterEncodedValue));
return this;
}
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
public UrlBuilder addQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new QueryParameter(queryParameterName, queryParameterEncodedValue);
}
value.addValue(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder clearQuery() {
if (query.isEmpty()) {
return this;
}
query.clear();
return this;
}
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, String> getQuery() {
final Map<String, String> singleKeyValueQuery =
this.query.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> {
QueryParameter parameter = e.getValue();
String value = null;
if (parameter != null) {
value = parameter.getValue();
}
return value;
}
));
return singleKeyValueQuery;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, QueryParameter> entry : query.entrySet()) {
for (String queryValue : entry.getValue().getValuesList()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
addQueryParameter(nameValue[0], nameValue[1]);
} else {
addQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Returns the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
* @return the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
*/
static Map<String, UrlBuilder> getParsedUrls() {
return PARSED_URLS;
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
if (PARSED_URLS.size() >= MAX_CACHE_SIZE) {
PARSED_URLS.clear();
}
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} |
Does using `QueryParameter` now introduce a potential NPE that didn't exist before if `queryParameterName` is null? Not something that needs to change but would be worth documenting. | public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new QueryParameter(queryParameterName, queryParameterEncodedValue));
return this;
} | return this; | public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new QueryParameter(queryParameterName, queryParameterEncodedValue));
return this;
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 10000;
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, QueryParameter> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
public UrlBuilder appendQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new QueryParameter(queryParameterName, queryParameterEncodedValue);
}
value.addValue(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
}
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder clearQuery() {
if (query != null && !query.isEmpty()) {
query.clear();
}
return this;
}
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, String> getQuery() {
final Map<String, String> singleKeyValueQuery =
this.query.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> {
QueryParameter parameter = e.getValue();
String value = null;
if (parameter != null) {
value = parameter.getValuesList().get(0);
}
return value;
}
));
return singleKeyValueQuery;
}
/**
* Get the query that has been assigned to this UrlBuilder, with {@link QueryParameter} as the
* value type.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, QueryParameter> getQueryParameters() {
return this.query;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, QueryParameter> entry : query.entrySet()) {
for (String queryValue : entry.getValue().getValuesList()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
appendQueryParameter(nameValue[0], nameValue[1]);
} else {
appendQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Returns the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
* @return the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
*/
static Map<String, UrlBuilder> getParsedUrls() {
return PARSED_URLS;
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
if (PARSED_URLS.size() >= MAX_CACHE_SIZE) {
PARSED_URLS.clear();
}
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 10000;
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, QueryParameter> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
public UrlBuilder addQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new QueryParameter(queryParameterName, queryParameterEncodedValue);
}
value.addValue(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
}
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder clearQuery() {
if (query.isEmpty()) {
return this;
}
query.clear();
return this;
}
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, String> getQuery() {
final Map<String, String> singleKeyValueQuery =
this.query.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> {
QueryParameter parameter = e.getValue();
String value = null;
if (parameter != null) {
value = parameter.getValue();
}
return value;
}
));
return singleKeyValueQuery;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, QueryParameter> entry : query.entrySet()) {
for (String queryValue : entry.getValue().getValuesList()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
addQueryParameter(nameValue[0], nameValue[1]);
} else {
addQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Returns the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
* @return the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
*/
static Map<String, UrlBuilder> getParsedUrls() {
return PARSED_URLS;
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
if (PARSED_URLS.size() >= MAX_CACHE_SIZE) {
PARSED_URLS.clear();
}
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} |
Is there a case where `query` would ever be null? Also, I think we need to have guards on clearing as it should be idempotent. | public UrlBuilder clearQuery() {
if (query != null && !query.isEmpty()) {
query.clear();
}
return this;
} | if (query != null && !query.isEmpty()) { | public UrlBuilder clearQuery() {
if (query.isEmpty()) {
return this;
}
query.clear();
return this;
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 10000;
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, QueryParameter> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new QueryParameter(queryParameterName, queryParameterEncodedValue));
return this;
}
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
public UrlBuilder appendQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new QueryParameter(queryParameterName, queryParameterEncodedValue);
}
value.addValue(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
}
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, String> getQuery() {
final Map<String, String> singleKeyValueQuery =
this.query.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> {
QueryParameter parameter = e.getValue();
String value = null;
if (parameter != null) {
value = parameter.getValuesList().get(0);
}
return value;
}
));
return singleKeyValueQuery;
}
/**
* Get the query that has been assigned to this UrlBuilder, with {@link QueryParameter} as the
* value type.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, QueryParameter> getQueryParameters() {
return this.query;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, QueryParameter> entry : query.entrySet()) {
for (String queryValue : entry.getValue().getValuesList()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
appendQueryParameter(nameValue[0], nameValue[1]);
} else {
appendQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Returns the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
* @return the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
*/
static Map<String, UrlBuilder> getParsedUrls() {
return PARSED_URLS;
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
if (PARSED_URLS.size() >= MAX_CACHE_SIZE) {
PARSED_URLS.clear();
}
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 10000;
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, QueryParameter> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new QueryParameter(queryParameterName, queryParameterEncodedValue));
return this;
}
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
public UrlBuilder addQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new QueryParameter(queryParameterName, queryParameterEncodedValue);
}
value.addValue(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
}
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, String> getQuery() {
final Map<String, String> singleKeyValueQuery =
this.query.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> {
QueryParameter parameter = e.getValue();
String value = null;
if (parameter != null) {
value = parameter.getValue();
}
return value;
}
));
return singleKeyValueQuery;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, QueryParameter> entry : query.entrySet()) {
for (String queryValue : entry.getValue().getValuesList()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
addQueryParameter(nameValue[0], nameValue[1]);
} else {
addQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Returns the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
* @return the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
*/
static Map<String, UrlBuilder> getParsedUrls() {
return PARSED_URLS;
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
if (PARSED_URLS.size() >= MAX_CACHE_SIZE) {
PARSED_URLS.clear();
}
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} |
Solved in the appendQueryParameter method as well. | public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new QueryParameter(queryParameterName, queryParameterEncodedValue));
return this;
} | return this; | public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new QueryParameter(queryParameterName, queryParameterEncodedValue));
return this;
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 10000;
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, QueryParameter> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
public UrlBuilder appendQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new QueryParameter(queryParameterName, queryParameterEncodedValue);
}
value.addValue(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
}
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder clearQuery() {
if (query != null && !query.isEmpty()) {
query.clear();
}
return this;
}
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, String> getQuery() {
final Map<String, String> singleKeyValueQuery =
this.query.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> {
QueryParameter parameter = e.getValue();
String value = null;
if (parameter != null) {
value = parameter.getValuesList().get(0);
}
return value;
}
));
return singleKeyValueQuery;
}
/**
* Get the query that has been assigned to this UrlBuilder, with {@link QueryParameter} as the
* value type.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, QueryParameter> getQueryParameters() {
return this.query;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, QueryParameter> entry : query.entrySet()) {
for (String queryValue : entry.getValue().getValuesList()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
appendQueryParameter(nameValue[0], nameValue[1]);
} else {
appendQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Returns the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
* @return the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
*/
static Map<String, UrlBuilder> getParsedUrls() {
return PARSED_URLS;
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
if (PARSED_URLS.size() >= MAX_CACHE_SIZE) {
PARSED_URLS.clear();
}
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 10000;
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, QueryParameter> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
public UrlBuilder addQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new QueryParameter(queryParameterName, queryParameterEncodedValue);
}
value.addValue(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
}
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder clearQuery() {
if (query.isEmpty()) {
return this;
}
query.clear();
return this;
}
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, String> getQuery() {
final Map<String, String> singleKeyValueQuery =
this.query.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> {
QueryParameter parameter = e.getValue();
String value = null;
if (parameter != null) {
value = parameter.getValue();
}
return value;
}
));
return singleKeyValueQuery;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, QueryParameter> entry : query.entrySet()) {
for (String queryValue : entry.getValue().getValuesList()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
addQueryParameter(nameValue[0], nameValue[1]);
} else {
addQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Returns the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
* @return the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
*/
static Map<String, UrlBuilder> getParsedUrls() {
return PARSED_URLS;
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
if (PARSED_URLS.size() >= MAX_CACHE_SIZE) {
PARSED_URLS.clear();
}
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} |
Solved. | public UrlBuilder clearQuery() {
if (query != null && !query.isEmpty()) {
query.clear();
}
return this;
} | if (query != null && !query.isEmpty()) { | public UrlBuilder clearQuery() {
if (query.isEmpty()) {
return this;
}
query.clear();
return this;
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 10000;
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, QueryParameter> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new QueryParameter(queryParameterName, queryParameterEncodedValue));
return this;
}
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
*/
public UrlBuilder appendQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new QueryParameter(queryParameterName, queryParameterEncodedValue);
}
value.addValue(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
}
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, String> getQuery() {
final Map<String, String> singleKeyValueQuery =
this.query.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> {
QueryParameter parameter = e.getValue();
String value = null;
if (parameter != null) {
value = parameter.getValuesList().get(0);
}
return value;
}
));
return singleKeyValueQuery;
}
/**
* Get the query that has been assigned to this UrlBuilder, with {@link QueryParameter} as the
* value type.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, QueryParameter> getQueryParameters() {
return this.query;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, QueryParameter> entry : query.entrySet()) {
for (String queryValue : entry.getValue().getValuesList()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
appendQueryParameter(nameValue[0], nameValue[1]);
} else {
appendQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Returns the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
* @return the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
*/
static Map<String, UrlBuilder> getParsedUrls() {
return PARSED_URLS;
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
if (PARSED_URLS.size() >= MAX_CACHE_SIZE) {
PARSED_URLS.clear();
}
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} | class UrlBuilder {
private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 10000;
private String scheme;
private String host;
private String port;
private String path;
private final Map<String, QueryParameter> query = new LinkedHashMap<>();
/**
* Set the scheme/protocol that will be used to build the final URL.
*
* @param scheme The scheme/protocol that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setScheme(String scheme) {
if (scheme == null || scheme.isEmpty()) {
this.scheme = null;
} else {
with(scheme, UrlTokenizerState.SCHEME);
}
return this;
}
/**
* Get the scheme/protocol that has been assigned to this UrlBuilder.
*
* @return the scheme/protocol that has been assigned to this UrlBuilder.
*/
public String getScheme() {
return scheme;
}
/**
* Set the host that will be used to build the final URL.
*
* @param host The host that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setHost(String host) {
if (host == null || host.isEmpty()) {
this.host = null;
} else {
with(host, UrlTokenizerState.SCHEME_OR_HOST);
}
return this;
}
/**
* Get the host that has been assigned to this UrlBuilder.
*
* @return the host that has been assigned to this UrlBuilder.
*/
public String getHost() {
return host;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(String port) {
if (port == null || port.isEmpty()) {
this.port = null;
} else {
with(port, UrlTokenizerState.PORT);
}
return this;
}
/**
* Set the port that will be used to build the final URL.
*
* @param port The port that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPort(int port) {
return setPort(Integer.toString(port));
}
/**
* Get the port that has been assigned to this UrlBuilder.
*
* @return the port that has been assigned to this UrlBuilder.
*/
public Integer getPort() {
return port == null ? null : Integer.valueOf(port);
}
/**
* Set the path that will be used to build the final URL.
*
* @param path The path that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setPath(String path) {
if (path == null || path.isEmpty()) {
this.path = null;
} else {
with(path, UrlTokenizerState.PATH);
}
return this;
}
/**
* Get the path that has been assigned to this UrlBuilder.
*
* @return the path that has been assigned to this UrlBuilder.
*/
public String getPath() {
return path;
}
/**
* Set the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.put(queryParameterName, new QueryParameter(queryParameterName, queryParameterEncodedValue));
return this;
}
/**
* Append the provided query parameter name and encoded value to query string for the final URL.
*
* @param queryParameterName The name of the query parameter.
* @param queryParameterEncodedValue The encoded value of the query parameter.
* @return The provided query parameter name and encoded value to query string for the final URL.
* @throws NullPointerException if {@code queryParameterName} or {@code queryParameterEncodedValue} are null.
*/
public UrlBuilder addQueryParameter(String queryParameterName, String queryParameterEncodedValue) {
query.compute(queryParameterName, (key, value) -> {
if (value == null) {
return new QueryParameter(queryParameterName, queryParameterEncodedValue);
}
value.addValue(queryParameterEncodedValue);
return value;
});
return this;
}
/**
* Set the query that will be used to build the final URL.
*
* @param query The query that will be used to build the final URL.
* @return This UrlBuilder so that multiple setters can be chained together.
*/
public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
}
/**
* Clear the query that will be used to build the final URL.
*
* @return This UrlBuilder so that multiple setters can be chained together.
*/
/**
* Get the query that has been assigned to this UrlBuilder.
*
* @return the query that has been assigned to this UrlBuilder.
*/
public Map<String, String> getQuery() {
final Map<String, String> singleKeyValueQuery =
this.query.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> {
QueryParameter parameter = e.getValue();
String value = null;
if (parameter != null) {
value = parameter.getValue();
}
return value;
}
));
return singleKeyValueQuery;
}
/**
* Returns the query string currently configured in this UrlBuilder instance.
* @return A String containing the currently configured query string.
*/
public String getQueryString() {
if (query.isEmpty()) {
return "";
}
StringBuilder queryBuilder = new StringBuilder("?");
for (Map.Entry<String, QueryParameter> entry : query.entrySet()) {
for (String queryValue : entry.getValue().getValuesList()) {
if (queryBuilder.length() > 1) {
queryBuilder.append("&");
}
queryBuilder.append(entry.getKey());
queryBuilder.append("=");
queryBuilder.append(queryValue);
}
}
return queryBuilder.toString();
}
private UrlBuilder with(String text, UrlTokenizerState startState) {
final UrlTokenizer tokenizer = new UrlTokenizer(text, startState);
while (tokenizer.next()) {
final UrlToken token = tokenizer.current();
final String tokenText = token.text();
final UrlTokenType tokenType = token.type();
switch (tokenType) {
case SCHEME:
scheme = emptyToNull(tokenText);
break;
case HOST:
host = emptyToNull(tokenText);
break;
case PORT:
port = emptyToNull(tokenText);
break;
case PATH:
final String tokenPath = emptyToNull(tokenText);
if (path == null || path.equals("/") || !tokenPath.equals("/")) {
path = tokenPath;
}
break;
case QUERY:
String queryString = emptyToNull(tokenText);
if (queryString != null) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
for (String entry : queryString.split("&")) {
String[] nameValue = entry.split("=");
if (nameValue.length == 2) {
addQueryParameter(nameValue[0], nameValue[1]);
} else {
addQueryParameter(nameValue[0], "");
}
}
}
break;
default:
break;
}
}
return this;
}
/**
* Get the URL that is being built.
*
* @return The URL that is being built.
* @throws MalformedURLException if the URL is not fully formed.
*/
public URL toUrl() throws MalformedURLException {
return new URL(toString());
}
/**
* Get the string representation of the URL that is being built.
*
* @return The string representation of the URL that is being built.
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
final boolean isAbsolutePath = path != null && (path.startsWith("http:
if (!isAbsolutePath) {
if (scheme != null) {
result.append(scheme);
if (!scheme.endsWith(":
result.append(":
}
}
if (host != null) {
result.append(host);
}
}
if (port != null) {
result.append(":");
result.append(port);
}
if (path != null) {
if (result.length() != 0 && !path.startsWith("/")) {
result.append('/');
}
result.append(path);
}
result.append(getQueryString());
return result.toString();
}
/**
* Returns the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
* @return the map of parsed URLs and their {@link UrlBuilder UrlBuilders}
*/
static Map<String, UrlBuilder> getParsedUrls() {
return PARSED_URLS;
}
/**
* Parses the passed {@code url} string into a UrlBuilder.
*
* @param url The URL string to parse.
* @return The UrlBuilder that was created from parsing the passed URL string.
*/
public static UrlBuilder parse(String url) {
/*
* Parsing the URL string into a UrlBuilder is a non-trivial operation and many calls into RestProxy will use
* the same root URL string. To save CPU costs we retain a parsed version of the URL string in memory. Given
* that UrlBuilder is mutable we must return a cloned version of the cached UrlBuilder.
*/
String concurrentSafeUrl = (url == null) ? "" : url;
if (PARSED_URLS.size() >= MAX_CACHE_SIZE) {
PARSED_URLS.clear();
}
return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u ->
new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy();
}
/**
* Parse a UrlBuilder from the provided URL object.
*
* @param url The URL object to parse.
* @return The UrlBuilder that was parsed from the URL object.
*/
public static UrlBuilder parse(URL url) {
final UrlBuilder result = new UrlBuilder();
if (url != null) {
final String protocol = url.getProtocol();
if (protocol != null && !protocol.isEmpty()) {
result.setScheme(protocol);
}
final String host = url.getHost();
if (host != null && !host.isEmpty()) {
result.setHost(host);
}
final int port = url.getPort();
if (port != -1) {
result.setPort(port);
}
final String path = url.getPath();
if (path != null && !path.isEmpty()) {
result.setPath(path);
}
final String query = url.getQuery();
if (query != null && !query.isEmpty()) {
result.setQuery(query);
}
}
return result;
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
private UrlBuilder copy() {
UrlBuilder copy = new UrlBuilder();
copy.scheme = this.scheme;
copy.host = this.host;
copy.path = this.path;
copy.port = this.port;
copy.query.putAll(this.query);
return copy;
}
} |
I actually think there is a logic bug in the new `QuerySubstitution` type. `QueryParam` added the new property of [multipleQueryParams](https://github.com/Azure/azure-sdk-for-java/pull/21203/files#diff-d24b7c212e712b54bc6e58f9e14369d076c4f474cf9df659b7a0b10f8fb1dd10R80) with a default of false to maintain backwards compatibility. `QuerySubstitution` takes that value [non-negated](https://github.com/Azure/azure-sdk-for-java/pull/21203/files#diff-48b6e5aa976e87e917eeb7f14a42e6eb66c880553d6a4f2f91d91285e53e7a5fR196) as the field `shouldMergeQueryParams`. Before this code block that value is [checked for the negated value](https://github.com/Azure/azure-sdk-for-java/pull/21203/files#diff-48b6e5aa976e87e917eeb7f14a42e6eb66c880553d6a4f2f91d91285e53e7a5fR289). This result in non-multiple query parameters being used as multiple query parameters, leading to the test error being seen before this last change. | public void setEncodedQueryParameters(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
if (swaggerMethodArguments == null) {
return;
}
for (QuerySubstitution substitution : querySubstitutions) {
final int parameterIndex = substitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[substitution.getMethodParameterIndex()];
List<Object> methodArguments = new ArrayList<Object>();
if (methodArgument instanceof List && !substitution.shouldMergeQueryParams()) {
if (methodArguments.isEmpty()) {
urlBuilder.setQueryParameter(substitution.getUrlParameterName(),
UrlEscapers.QUERY_ESCAPER.escape("[]"));
} else {
methodArguments.addAll((List<Object>) methodArgument);
}
} else {
methodArguments.add(methodArgument);
}
for (Object methodArgumentUnconverted : methodArguments) {
String parameterValue = serialize(serializer, methodArgumentUnconverted);
if (parameterValue != null) {
if (substitution.shouldEncode()) {
parameterValue = UrlEscapers.QUERY_ESCAPER.escape(parameterValue);
}
urlBuilder.appendQueryParameter(substitution.getUrlParameterName(), parameterValue);
}
}
}
}
} | UrlEscapers.QUERY_ESCAPER.escape("[]")); | public void setEncodedQueryParameters(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
if (swaggerMethodArguments == null) {
return;
}
for (QuerySubstitution substitution : querySubstitutions) {
final int parameterIndex = substitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[substitution.getMethodParameterIndex()];
if (substitution.mergeParameters() && methodArgument instanceof List) {
List<Object> methodArguments = (List<Object>) methodArgument;
for (Object argument : methodArguments) {
addSerializedQueryParameter(serializer, argument, substitution.shouldEncode(),
urlBuilder, substitution.getUrlParameterName());
}
} else {
addSerializedQueryParameter(serializer, methodArgument, substitution.shouldEncode(),
urlBuilder, substitution.getUrlParameterName());
}
}
}
} | class SwaggerMethodParser implements HttpResponseDecodeData {
private static final Pattern PATTERN_COLON_SLASH_SLASH = Pattern.compile(":
private final SerializerAdapter serializer;
private final String rawHost;
private final String fullyQualifiedMethodName;
private final HttpMethod httpMethod;
private final String relativePath;
private final List<Substitution> hostSubstitutions = new ArrayList<>();
private final List<Substitution> pathSubstitutions = new ArrayList<>();
private final List<QuerySubstitution> querySubstitutions = new ArrayList<>();
private final List<Substitution> formSubstitutions = new ArrayList<>();
private final List<Substitution> headerSubstitutions = new ArrayList<>();
private final HttpHeaders headers = new HttpHeaders();
private final Integer bodyContentMethodParameterIndex;
private final String bodyContentType;
private final Type bodyJavaType;
private final BitSet expectedStatusCodes;
private final Type returnType;
private final Type returnValueWireType;
private final UnexpectedResponseExceptionType[] unexpectedResponseExceptionTypes;
private Map<Integer, UnexpectedExceptionInformation> exceptionMapping;
private UnexpectedExceptionInformation defaultException;
/**
* Create a SwaggerMethodParser object using the provided fully qualified method name.
*
* @param swaggerMethod the Swagger method to parse.
* @param rawHost the raw host value from the @Host annotation. Before this can be used as the host value in an HTTP
* request, it must be processed through the possible host substitutions.
*/
SwaggerMethodParser(Method swaggerMethod, String rawHost) {
this(swaggerMethod, rawHost, JacksonAdapter.createDefaultSerializerAdapter());
}
SwaggerMethodParser(Method swaggerMethod, String rawHost, SerializerAdapter serializer) {
this.serializer = serializer;
this.rawHost = rawHost;
final Class<?> swaggerInterface = swaggerMethod.getDeclaringClass();
fullyQualifiedMethodName = swaggerInterface.getName() + "." + swaggerMethod.getName();
if (swaggerMethod.isAnnotationPresent(Get.class)) {
this.httpMethod = HttpMethod.GET;
this.relativePath = swaggerMethod.getAnnotation(Get.class).value();
} else if (swaggerMethod.isAnnotationPresent(Put.class)) {
this.httpMethod = HttpMethod.PUT;
this.relativePath = swaggerMethod.getAnnotation(Put.class).value();
} else if (swaggerMethod.isAnnotationPresent(Head.class)) {
this.httpMethod = HttpMethod.HEAD;
this.relativePath = swaggerMethod.getAnnotation(Head.class).value();
} else if (swaggerMethod.isAnnotationPresent(Delete.class)) {
this.httpMethod = HttpMethod.DELETE;
this.relativePath = swaggerMethod.getAnnotation(Delete.class).value();
} else if (swaggerMethod.isAnnotationPresent(Post.class)) {
this.httpMethod = HttpMethod.POST;
this.relativePath = swaggerMethod.getAnnotation(Post.class).value();
} else if (swaggerMethod.isAnnotationPresent(Patch.class)) {
this.httpMethod = HttpMethod.PATCH;
this.relativePath = swaggerMethod.getAnnotation(Patch.class).value();
} else {
throw new MissingRequiredAnnotationException(Arrays.asList(Get.class, Put.class, Head.class,
Delete.class, Post.class, Patch.class), swaggerMethod);
}
returnType = swaggerMethod.getGenericReturnType();
final ReturnValueWireType returnValueWireTypeAnnotation =
swaggerMethod.getAnnotation(ReturnValueWireType.class);
if (returnValueWireTypeAnnotation != null) {
Class<?> returnValueWireType = returnValueWireTypeAnnotation.value();
if (returnValueWireType == Base64Url.class
|| returnValueWireType == UnixTime.class
|| returnValueWireType == DateTimeRfc1123.class) {
this.returnValueWireType = returnValueWireType;
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, List.class)) {
this.returnValueWireType = returnValueWireType.getGenericInterfaces()[0];
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, Page.class)) {
this.returnValueWireType = returnValueWireType;
} else {
this.returnValueWireType = null;
}
} else {
this.returnValueWireType = null;
}
if (swaggerMethod.isAnnotationPresent(Headers.class)) {
final Headers headersAnnotation = swaggerMethod.getAnnotation(Headers.class);
final String[] headers = headersAnnotation.value();
for (final String header : headers) {
final int colonIndex = header.indexOf(":");
if (colonIndex >= 0) {
final String headerName = header.substring(0, colonIndex).trim();
if (!headerName.isEmpty()) {
final String headerValue = header.substring(colonIndex + 1).trim();
if (!headerValue.isEmpty()) {
if (headerValue.contains(",")) {
this.headers.set(headerName, Arrays.asList(headerValue.split(",")));
} else {
this.headers.set(headerName, headerValue);
}
}
}
}
}
}
final ExpectedResponses expectedResponses = swaggerMethod.getAnnotation(ExpectedResponses.class);
if (expectedResponses != null && expectedResponses.value().length > 0) {
expectedStatusCodes = new BitSet();
for (int code : expectedResponses.value()) {
expectedStatusCodes.set(code);
}
} else {
expectedStatusCodes = null;
}
unexpectedResponseExceptionTypes = swaggerMethod.getAnnotationsByType(UnexpectedResponseExceptionType.class);
Integer bodyContentMethodParameterIndex = null;
String bodyContentType = null;
Type bodyJavaType = null;
final Annotation[][] allParametersAnnotations = swaggerMethod.getParameterAnnotations();
for (int parameterIndex = 0; parameterIndex < allParametersAnnotations.length; ++parameterIndex) {
final Annotation[] parameterAnnotations = swaggerMethod.getParameterAnnotations()[parameterIndex];
for (final Annotation annotation : parameterAnnotations) {
final Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.equals(HostParam.class)) {
final HostParam hostParamAnnotation = (HostParam) annotation;
hostSubstitutions.add(new Substitution(hostParamAnnotation.value(), parameterIndex,
!hostParamAnnotation.encoded()));
} else if (annotationType.equals(PathParam.class)) {
final PathParam pathParamAnnotation = (PathParam) annotation;
pathSubstitutions.add(new Substitution(pathParamAnnotation.value(), parameterIndex,
!pathParamAnnotation.encoded()));
} else if (annotationType.equals(QueryParam.class)) {
final QueryParam queryParamAnnotation = (QueryParam) annotation;
querySubstitutions.add(new QuerySubstitution(queryParamAnnotation.value(), parameterIndex,
!queryParamAnnotation.encoded(), queryParamAnnotation.multipleQueryParams()));
} else if (annotationType.equals(HeaderParam.class)) {
final HeaderParam headerParamAnnotation = (HeaderParam) annotation;
headerSubstitutions.add(new Substitution(headerParamAnnotation.value(), parameterIndex,
false));
} else if (annotationType.equals(BodyParam.class)) {
final BodyParam bodyParamAnnotation = (BodyParam) annotation;
bodyContentMethodParameterIndex = parameterIndex;
bodyContentType = bodyParamAnnotation.value();
bodyJavaType = swaggerMethod.getGenericParameterTypes()[parameterIndex];
} else if (annotationType.equals(FormParam.class)) {
final FormParam formParamAnnotation = (FormParam) annotation;
formSubstitutions.add(new Substitution(formParamAnnotation.value(), parameterIndex,
!formParamAnnotation.encoded()));
bodyContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
bodyJavaType = String.class;
}
}
}
this.bodyContentMethodParameterIndex = bodyContentMethodParameterIndex;
this.bodyContentType = bodyContentType;
this.bodyJavaType = bodyJavaType;
}
/**
* Get the fully qualified method that was called to invoke this HTTP request.
*
* @return the fully qualified method that was called to invoke this HTTP request
*/
public String getFullyQualifiedMethodName() {
return fullyQualifiedMethodName;
}
/**
* Get the HTTP method that will be used to complete the Swagger method's request.
*
* @return the HTTP method that will be used to complete the Swagger method's request
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Sets the scheme and host to use for HTTP requests for this Swagger method.
*
* @param swaggerMethodArguments The arguments to use for scheme and host substitutions.
* @param urlBuilder The {@link UrlBuilder} that will have its scheme and host set.
*/
public void setSchemeAndHost(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments);
final String[] substitutedHostParts = PATTERN_COLON_SLASH_SLASH.split(substitutedHost);
if (substitutedHostParts.length >= 2) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHostParts[1]);
} else if (substitutedHostParts.length == 1) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHost);
} else {
urlBuilder.setHost(substitutedHost);
}
}
/**
* Get the path that will be used to complete the Swagger method's request.
*
* @param methodArguments the method arguments to use with the path substitutions
* @return the path value with its placeholders replaced by the matching substitutions
*/
public String setPath(Object[] methodArguments) {
return applySubstitutions(relativePath, pathSubstitutions, methodArguments);
}
/**
* Sets the encoded query parameters that have been added to this value based on the provided method arguments into
* the passed {@link UrlBuilder}.
*
* @param swaggerMethodArguments the arguments that will be used to create the query parameters' values
* @param urlBuilder The {@link UrlBuilder} where the encoded query parameters will be set.
*/
@SuppressWarnings("unchecked")
/**
* Sets the headers that have been added to this value based on the provided method arguments into the passed
* {@link HttpHeaders}.
*
* @param swaggerMethodArguments The arguments that will be used to create the headers' values.
* @param httpHeaders The {@link HttpHeaders} where the header values will be set.
*/
public void setHeaders(Object[] swaggerMethodArguments, HttpHeaders httpHeaders) {
for (HttpHeader header : headers) {
httpHeaders.set(header.getName(), header.getValuesList());
}
if (swaggerMethodArguments == null) {
return;
}
for (Substitution headerSubstitution : headerSubstitutions) {
final int parameterIndex = headerSubstitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[headerSubstitution.getMethodParameterIndex()];
if (methodArgument instanceof Map) {
@SuppressWarnings("unchecked") final Map<String, ?> headerCollection =
(Map<String, ?>) methodArgument;
final String headerCollectionPrefix = headerSubstitution.getUrlParameterName();
for (final Map.Entry<String, ?> headerCollectionEntry : headerCollection.entrySet()) {
final String headerName = headerCollectionPrefix + headerCollectionEntry.getKey();
final String headerValue = serialize(serializer, headerCollectionEntry.getValue());
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
} else {
final String headerName = headerSubstitution.getUrlParameterName();
final String headerValue = serialize(serializer, methodArgument);
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
}
}
}
/**
* Get the {@link Context} passed into the proxy method.
*
* @param swaggerMethodArguments the arguments passed to the proxy method
* @return the context, or {@link Context
*/
public Context setContext(Object[] swaggerMethodArguments) {
Context context = CoreUtils.findFirstOfType(swaggerMethodArguments, Context.class);
return (context != null) ? context : Context.NONE;
}
/**
* Get whether or not the provided response status code is one of the expected status codes for this Swagger
* method.
*
* 1. If the returned int[] is null, then all 2XX status codes are considered as success code.
* 2. If the returned int[] is not-null, only the codes in the array are considered as success code.
*
* @param statusCode the status code that was returned in the HTTP response
* @return whether or not the provided response status code is one of the expected status codes for this Swagger
* method
*/
@Override
public boolean isExpectedResponseStatusCode(final int statusCode) {
return expectedStatusCodes == null
? statusCode < 400
: expectedStatusCodes.get(statusCode);
}
/**
* Get the {@link UnexpectedExceptionInformation} that will be used to generate a RestException if the HTTP response
* status code is not one of the expected status codes.
*
* If an UnexpectedExceptionInformation is not found for the status code the default UnexpectedExceptionInformation
* will be returned.
*
* @param code Exception HTTP status code return from a REST API.
* @return the UnexpectedExceptionInformation to generate an exception to throw or return.
*/
@Override
public UnexpectedExceptionInformation getUnexpectedException(int code) {
if (exceptionMapping == null) {
exceptionMapping = processUnexpectedResponseExceptionTypes();
}
return exceptionMapping.getOrDefault(code, defaultException);
}
/**
* Get the object to be used as the value of the HTTP request.
*
* @param swaggerMethodArguments the method arguments to get the value object from
* @return the object that will be used as the body of the HTTP request
*/
public Object setBody(Object[] swaggerMethodArguments) {
Object result = null;
if (bodyContentMethodParameterIndex != null
&& swaggerMethodArguments != null
&& 0 <= bodyContentMethodParameterIndex
&& bodyContentMethodParameterIndex < swaggerMethodArguments.length) {
result = swaggerMethodArguments[bodyContentMethodParameterIndex];
}
if (!CoreUtils.isNullOrEmpty(formSubstitutions) && swaggerMethodArguments != null) {
result = formSubstitutions.stream()
.map(substitution -> serializeFormData(serializer, substitution.getUrlParameterName(),
swaggerMethodArguments[substitution.getMethodParameterIndex()], substitution.shouldEncode()))
.filter(Objects::nonNull)
.collect(Collectors.joining("&"));
}
return result;
}
/**
* Get the Content-Type of the body of this Swagger method.
*
* @return the Content-Type of the body of this Swagger method
*/
public String getBodyContentType() {
return bodyContentType;
}
/**
* Get the return type for the method that this object describes.
*
* @return the return type for the method that this object describes.
*/
@Override
public Type getReturnType() {
return returnType;
}
/**
* Get the type of the body parameter to this method, if present.
*
* @return the return type of the body parameter to this method
*/
public Type getBodyJavaType() {
return bodyJavaType;
}
/**
* Get the type that the return value will be send across the network as. If returnValueWireType is not null, then
* the raw HTTP response body will need to parsed to this type and then converted to the actual returnType.
*
* @return the type that the raw HTTP response body will be sent as
*/
@Override
public Type getReturnValueWireType() {
return returnValueWireType;
}
private static String serialize(SerializerAdapter serializer, Object value) {
if (value == null) {
return null;
}
if (value instanceof String) {
return (String) value;
} else {
return serializer.serializeRaw(value);
}
}
private static String serializeFormData(SerializerAdapter serializer, String key, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String encodedKey = UrlEscapers.FORM_ESCAPER.escape(key);
if (value instanceof List<?>) {
return ((List<?>) value).stream()
.map(element -> serializeAndEncodeFormValue(serializer, element, shouldEncode))
.filter(Objects::nonNull)
.map(formValue -> encodedKey + "=" + formValue)
.collect(Collectors.joining("&"));
} else {
return encodedKey + "=" + serializeAndEncodeFormValue(serializer, value, shouldEncode);
}
}
private static String serializeAndEncodeFormValue(SerializerAdapter serializer, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String serializedValue = serializer.serializeRaw(value);
return shouldEncode ? UrlEscapers.FORM_ESCAPER.escape(serializedValue) : serializedValue;
}
private String applySubstitutions(String originalValue, Iterable<Substitution> substitutions,
Object[] methodArguments) {
String result = originalValue;
if (methodArguments != null) {
for (Substitution substitution : substitutions) {
final int substitutionParameterIndex = substitution.getMethodParameterIndex();
if (0 <= substitutionParameterIndex && substitutionParameterIndex < methodArguments.length) {
final Object methodArgument = methodArguments[substitutionParameterIndex];
String substitutionValue = serialize(serializer, methodArgument);
if (substitutionValue != null && !substitutionValue.isEmpty() && substitution.shouldEncode()) {
substitutionValue = UrlEscapers.PATH_ESCAPER.escape(substitutionValue);
}
if (substitutionValue == null) {
substitutionValue = "";
}
result = result.replace("{" + substitution.getUrlParameterName() + "}", substitutionValue);
}
}
}
return result;
}
private Map<Integer, UnexpectedExceptionInformation> processUnexpectedResponseExceptionTypes() {
HashMap<Integer, UnexpectedExceptionInformation> exceptionHashMap = new HashMap<>();
for (UnexpectedResponseExceptionType exceptionAnnotation : unexpectedResponseExceptionTypes) {
UnexpectedExceptionInformation exception = new UnexpectedExceptionInformation(exceptionAnnotation.value());
if (exceptionAnnotation.code().length == 0) {
defaultException = exception;
} else {
for (int statusCode : exceptionAnnotation.code()) {
exceptionHashMap.put(statusCode, exception);
}
}
}
if (defaultException == null) {
defaultException = new UnexpectedExceptionInformation(HttpResponseException.class);
}
return exceptionHashMap;
}
} | class SwaggerMethodParser implements HttpResponseDecodeData {
private static final Pattern PATTERN_COLON_SLASH_SLASH = Pattern.compile(":
private final SerializerAdapter serializer;
private final String rawHost;
private final String fullyQualifiedMethodName;
private final HttpMethod httpMethod;
private final String relativePath;
private final List<Substitution> hostSubstitutions = new ArrayList<>();
private final List<Substitution> pathSubstitutions = new ArrayList<>();
private final List<QuerySubstitution> querySubstitutions = new ArrayList<>();
private final List<Substitution> formSubstitutions = new ArrayList<>();
private final List<Substitution> headerSubstitutions = new ArrayList<>();
private final HttpHeaders headers = new HttpHeaders();
private final Integer bodyContentMethodParameterIndex;
private final String bodyContentType;
private final Type bodyJavaType;
private final BitSet expectedStatusCodes;
private final Type returnType;
private final Type returnValueWireType;
private final UnexpectedResponseExceptionType[] unexpectedResponseExceptionTypes;
private Map<Integer, UnexpectedExceptionInformation> exceptionMapping;
private UnexpectedExceptionInformation defaultException;
/**
* Create a SwaggerMethodParser object using the provided fully qualified method name.
*
* @param swaggerMethod the Swagger method to parse.
* @param rawHost the raw host value from the @Host annotation. Before this can be used as the host value in an HTTP
* request, it must be processed through the possible host substitutions.
*/
SwaggerMethodParser(Method swaggerMethod, String rawHost) {
this(swaggerMethod, rawHost, JacksonAdapter.createDefaultSerializerAdapter());
}
SwaggerMethodParser(Method swaggerMethod, String rawHost, SerializerAdapter serializer) {
this.serializer = serializer;
this.rawHost = rawHost;
final Class<?> swaggerInterface = swaggerMethod.getDeclaringClass();
fullyQualifiedMethodName = swaggerInterface.getName() + "." + swaggerMethod.getName();
if (swaggerMethod.isAnnotationPresent(Get.class)) {
this.httpMethod = HttpMethod.GET;
this.relativePath = swaggerMethod.getAnnotation(Get.class).value();
} else if (swaggerMethod.isAnnotationPresent(Put.class)) {
this.httpMethod = HttpMethod.PUT;
this.relativePath = swaggerMethod.getAnnotation(Put.class).value();
} else if (swaggerMethod.isAnnotationPresent(Head.class)) {
this.httpMethod = HttpMethod.HEAD;
this.relativePath = swaggerMethod.getAnnotation(Head.class).value();
} else if (swaggerMethod.isAnnotationPresent(Delete.class)) {
this.httpMethod = HttpMethod.DELETE;
this.relativePath = swaggerMethod.getAnnotation(Delete.class).value();
} else if (swaggerMethod.isAnnotationPresent(Post.class)) {
this.httpMethod = HttpMethod.POST;
this.relativePath = swaggerMethod.getAnnotation(Post.class).value();
} else if (swaggerMethod.isAnnotationPresent(Patch.class)) {
this.httpMethod = HttpMethod.PATCH;
this.relativePath = swaggerMethod.getAnnotation(Patch.class).value();
} else {
throw new MissingRequiredAnnotationException(Arrays.asList(Get.class, Put.class, Head.class,
Delete.class, Post.class, Patch.class), swaggerMethod);
}
returnType = swaggerMethod.getGenericReturnType();
final ReturnValueWireType returnValueWireTypeAnnotation =
swaggerMethod.getAnnotation(ReturnValueWireType.class);
if (returnValueWireTypeAnnotation != null) {
Class<?> returnValueWireType = returnValueWireTypeAnnotation.value();
if (returnValueWireType == Base64Url.class
|| returnValueWireType == UnixTime.class
|| returnValueWireType == DateTimeRfc1123.class) {
this.returnValueWireType = returnValueWireType;
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, List.class)) {
this.returnValueWireType = returnValueWireType.getGenericInterfaces()[0];
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, Page.class)) {
this.returnValueWireType = returnValueWireType;
} else {
this.returnValueWireType = null;
}
} else {
this.returnValueWireType = null;
}
if (swaggerMethod.isAnnotationPresent(Headers.class)) {
final Headers headersAnnotation = swaggerMethod.getAnnotation(Headers.class);
final String[] headers = headersAnnotation.value();
for (final String header : headers) {
final int colonIndex = header.indexOf(":");
if (colonIndex >= 0) {
final String headerName = header.substring(0, colonIndex).trim();
if (!headerName.isEmpty()) {
final String headerValue = header.substring(colonIndex + 1).trim();
if (!headerValue.isEmpty()) {
if (headerValue.contains(",")) {
this.headers.set(headerName, Arrays.asList(headerValue.split(",")));
} else {
this.headers.set(headerName, headerValue);
}
}
}
}
}
}
final ExpectedResponses expectedResponses = swaggerMethod.getAnnotation(ExpectedResponses.class);
if (expectedResponses != null && expectedResponses.value().length > 0) {
expectedStatusCodes = new BitSet();
for (int code : expectedResponses.value()) {
expectedStatusCodes.set(code);
}
} else {
expectedStatusCodes = null;
}
unexpectedResponseExceptionTypes = swaggerMethod.getAnnotationsByType(UnexpectedResponseExceptionType.class);
Integer bodyContentMethodParameterIndex = null;
String bodyContentType = null;
Type bodyJavaType = null;
final Annotation[][] allParametersAnnotations = swaggerMethod.getParameterAnnotations();
for (int parameterIndex = 0; parameterIndex < allParametersAnnotations.length; ++parameterIndex) {
final Annotation[] parameterAnnotations = swaggerMethod.getParameterAnnotations()[parameterIndex];
for (final Annotation annotation : parameterAnnotations) {
final Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.equals(HostParam.class)) {
final HostParam hostParamAnnotation = (HostParam) annotation;
hostSubstitutions.add(new Substitution(hostParamAnnotation.value(), parameterIndex,
!hostParamAnnotation.encoded()));
} else if (annotationType.equals(PathParam.class)) {
final PathParam pathParamAnnotation = (PathParam) annotation;
pathSubstitutions.add(new Substitution(pathParamAnnotation.value(), parameterIndex,
!pathParamAnnotation.encoded()));
} else if (annotationType.equals(QueryParam.class)) {
final QueryParam queryParamAnnotation = (QueryParam) annotation;
querySubstitutions.add(new QuerySubstitution(queryParamAnnotation.value(), parameterIndex,
!queryParamAnnotation.encoded(), queryParamAnnotation.multipleQueryParams()));
} else if (annotationType.equals(HeaderParam.class)) {
final HeaderParam headerParamAnnotation = (HeaderParam) annotation;
headerSubstitutions.add(new Substitution(headerParamAnnotation.value(), parameterIndex,
false));
} else if (annotationType.equals(BodyParam.class)) {
final BodyParam bodyParamAnnotation = (BodyParam) annotation;
bodyContentMethodParameterIndex = parameterIndex;
bodyContentType = bodyParamAnnotation.value();
bodyJavaType = swaggerMethod.getGenericParameterTypes()[parameterIndex];
} else if (annotationType.equals(FormParam.class)) {
final FormParam formParamAnnotation = (FormParam) annotation;
formSubstitutions.add(new Substitution(formParamAnnotation.value(), parameterIndex,
!formParamAnnotation.encoded()));
bodyContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
bodyJavaType = String.class;
}
}
}
this.bodyContentMethodParameterIndex = bodyContentMethodParameterIndex;
this.bodyContentType = bodyContentType;
this.bodyJavaType = bodyJavaType;
}
/**
* Get the fully qualified method that was called to invoke this HTTP request.
*
* @return the fully qualified method that was called to invoke this HTTP request
*/
public String getFullyQualifiedMethodName() {
return fullyQualifiedMethodName;
}
/**
* Get the HTTP method that will be used to complete the Swagger method's request.
*
* @return the HTTP method that will be used to complete the Swagger method's request
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Sets the scheme and host to use for HTTP requests for this Swagger method.
*
* @param swaggerMethodArguments The arguments to use for scheme and host substitutions.
* @param urlBuilder The {@link UrlBuilder} that will have its scheme and host set.
*/
public void setSchemeAndHost(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments);
final String[] substitutedHostParts = PATTERN_COLON_SLASH_SLASH.split(substitutedHost);
if (substitutedHostParts.length >= 2) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHostParts[1]);
} else if (substitutedHostParts.length == 1) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHost);
} else {
urlBuilder.setHost(substitutedHost);
}
}
/**
* Get the path that will be used to complete the Swagger method's request.
*
* @param methodArguments the method arguments to use with the path substitutions
* @return the path value with its placeholders replaced by the matching substitutions
*/
public String setPath(Object[] methodArguments) {
return applySubstitutions(relativePath, pathSubstitutions, methodArguments);
}
/**
* Sets the encoded query parameters that have been added to this value based on the provided method arguments into
* the passed {@link UrlBuilder}.
*
* @param swaggerMethodArguments the arguments that will be used to create the query parameters' values
* @param urlBuilder The {@link UrlBuilder} where the encoded query parameters will be set.
*/
@SuppressWarnings("unchecked")
/**
* Sets the headers that have been added to this value based on the provided method arguments into the passed
* {@link HttpHeaders}.
*
* @param swaggerMethodArguments The arguments that will be used to create the headers' values.
* @param httpHeaders The {@link HttpHeaders} where the header values will be set.
*/
public void setHeaders(Object[] swaggerMethodArguments, HttpHeaders httpHeaders) {
for (HttpHeader header : headers) {
httpHeaders.set(header.getName(), header.getValuesList());
}
if (swaggerMethodArguments == null) {
return;
}
for (Substitution headerSubstitution : headerSubstitutions) {
final int parameterIndex = headerSubstitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[headerSubstitution.getMethodParameterIndex()];
if (methodArgument instanceof Map) {
@SuppressWarnings("unchecked") final Map<String, ?> headerCollection =
(Map<String, ?>) methodArgument;
final String headerCollectionPrefix = headerSubstitution.getUrlParameterName();
for (final Map.Entry<String, ?> headerCollectionEntry : headerCollection.entrySet()) {
final String headerName = headerCollectionPrefix + headerCollectionEntry.getKey();
final String headerValue = serialize(serializer, headerCollectionEntry.getValue());
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
} else {
final String headerName = headerSubstitution.getUrlParameterName();
final String headerValue = serialize(serializer, methodArgument);
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
}
}
}
/**
* Get the {@link Context} passed into the proxy method.
*
* @param swaggerMethodArguments the arguments passed to the proxy method
* @return the context, or {@link Context
*/
public Context setContext(Object[] swaggerMethodArguments) {
Context context = CoreUtils.findFirstOfType(swaggerMethodArguments, Context.class);
return (context != null) ? context : Context.NONE;
}
/**
* Get whether or not the provided response status code is one of the expected status codes for this Swagger
* method.
*
* 1. If the returned int[] is null, then all 2XX status codes are considered as success code.
* 2. If the returned int[] is not-null, only the codes in the array are considered as success code.
*
* @param statusCode the status code that was returned in the HTTP response
* @return whether or not the provided response status code is one of the expected status codes for this Swagger
* method
*/
@Override
public boolean isExpectedResponseStatusCode(final int statusCode) {
return expectedStatusCodes == null
? statusCode < 400
: expectedStatusCodes.get(statusCode);
}
/**
* Get the {@link UnexpectedExceptionInformation} that will be used to generate a RestException if the HTTP response
* status code is not one of the expected status codes.
*
* If an UnexpectedExceptionInformation is not found for the status code the default UnexpectedExceptionInformation
* will be returned.
*
* @param code Exception HTTP status code return from a REST API.
* @return the UnexpectedExceptionInformation to generate an exception to throw or return.
*/
@Override
public UnexpectedExceptionInformation getUnexpectedException(int code) {
if (exceptionMapping == null) {
exceptionMapping = processUnexpectedResponseExceptionTypes();
}
return exceptionMapping.getOrDefault(code, defaultException);
}
/**
* Get the object to be used as the value of the HTTP request.
*
* @param swaggerMethodArguments the method arguments to get the value object from
* @return the object that will be used as the body of the HTTP request
*/
public Object setBody(Object[] swaggerMethodArguments) {
Object result = null;
if (bodyContentMethodParameterIndex != null
&& swaggerMethodArguments != null
&& 0 <= bodyContentMethodParameterIndex
&& bodyContentMethodParameterIndex < swaggerMethodArguments.length) {
result = swaggerMethodArguments[bodyContentMethodParameterIndex];
}
if (!CoreUtils.isNullOrEmpty(formSubstitutions) && swaggerMethodArguments != null) {
result = formSubstitutions.stream()
.map(substitution -> serializeFormData(serializer, substitution.getUrlParameterName(),
swaggerMethodArguments[substitution.getMethodParameterIndex()], substitution.shouldEncode()))
.filter(Objects::nonNull)
.collect(Collectors.joining("&"));
}
return result;
}
/**
* Get the Content-Type of the body of this Swagger method.
*
* @return the Content-Type of the body of this Swagger method
*/
public String getBodyContentType() {
return bodyContentType;
}
/**
* Get the return type for the method that this object describes.
*
* @return the return type for the method that this object describes.
*/
@Override
public Type getReturnType() {
return returnType;
}
/**
* Get the type of the body parameter to this method, if present.
*
* @return the return type of the body parameter to this method
*/
public Type getBodyJavaType() {
return bodyJavaType;
}
/**
* Get the type that the return value will be send across the network as. If returnValueWireType is not null, then
* the raw HTTP response body will need to parsed to this type and then converted to the actual returnType.
*
* @return the type that the raw HTTP response body will be sent as
*/
@Override
public Type getReturnValueWireType() {
return returnValueWireType;
}
private static void addSerializedQueryParameter(SerializerAdapter adapter, Object value, boolean shouldEncode,
UrlBuilder urlBuilder, String parameterName) {
String parameterValue = serialize(adapter, value);
if (parameterValue != null) {
if (shouldEncode) {
parameterValue = UrlEscapers.QUERY_ESCAPER.escape(parameterValue);
}
urlBuilder.addQueryParameter(parameterName, parameterValue);
}
}
private static String serialize(SerializerAdapter serializer, Object value) {
if (value == null) {
return null;
}
if (value instanceof String) {
return (String) value;
} else {
return serializer.serializeRaw(value);
}
}
private static String serializeFormData(SerializerAdapter serializer, String key, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String encodedKey = UrlEscapers.FORM_ESCAPER.escape(key);
if (value instanceof List<?>) {
return ((List<?>) value).stream()
.map(element -> serializeAndEncodeFormValue(serializer, element, shouldEncode))
.filter(Objects::nonNull)
.map(formValue -> encodedKey + "=" + formValue)
.collect(Collectors.joining("&"));
} else {
return encodedKey + "=" + serializeAndEncodeFormValue(serializer, value, shouldEncode);
}
}
private static String serializeAndEncodeFormValue(SerializerAdapter serializer, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String serializedValue = serializer.serializeRaw(value);
return shouldEncode ? UrlEscapers.FORM_ESCAPER.escape(serializedValue) : serializedValue;
}
private String applySubstitutions(String originalValue, Iterable<Substitution> substitutions,
Object[] methodArguments) {
String result = originalValue;
if (methodArguments != null) {
for (Substitution substitution : substitutions) {
final int substitutionParameterIndex = substitution.getMethodParameterIndex();
if (0 <= substitutionParameterIndex && substitutionParameterIndex < methodArguments.length) {
final Object methodArgument = methodArguments[substitutionParameterIndex];
String substitutionValue = serialize(serializer, methodArgument);
if (substitutionValue != null && !substitutionValue.isEmpty() && substitution.shouldEncode()) {
substitutionValue = UrlEscapers.PATH_ESCAPER.escape(substitutionValue);
}
if (substitutionValue == null) {
substitutionValue = "";
}
result = result.replace("{" + substitution.getUrlParameterName() + "}", substitutionValue);
}
}
}
return result;
}
private Map<Integer, UnexpectedExceptionInformation> processUnexpectedResponseExceptionTypes() {
HashMap<Integer, UnexpectedExceptionInformation> exceptionHashMap = new HashMap<>();
for (UnexpectedResponseExceptionType exceptionAnnotation : unexpectedResponseExceptionTypes) {
UnexpectedExceptionInformation exception = new UnexpectedExceptionInformation(exceptionAnnotation.value());
if (exceptionAnnotation.code().length == 0) {
defaultException = exception;
} else {
for (int statusCode : exceptionAnnotation.code()) {
exceptionHashMap.put(statusCode, exception);
}
}
}
if (defaultException == null) {
defaultException = new UnexpectedExceptionInformation(HttpResponseException.class);
}
return exceptionHashMap;
}
} |
@alzimmermsft @v-ddaian good catch. Made the change and now all checks are passing. | public void setEncodedQueryParameters(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
if (swaggerMethodArguments == null) {
return;
}
for (QuerySubstitution substitution : querySubstitutions) {
final int parameterIndex = substitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[substitution.getMethodParameterIndex()];
List<Object> methodArguments = new ArrayList<Object>();
if (methodArgument instanceof List && !substitution.shouldMergeQueryParams()) {
if (methodArguments.isEmpty()) {
urlBuilder.setQueryParameter(substitution.getUrlParameterName(),
UrlEscapers.QUERY_ESCAPER.escape("[]"));
} else {
methodArguments.addAll((List<Object>) methodArgument);
}
} else {
methodArguments.add(methodArgument);
}
for (Object methodArgumentUnconverted : methodArguments) {
String parameterValue = serialize(serializer, methodArgumentUnconverted);
if (parameterValue != null) {
if (substitution.shouldEncode()) {
parameterValue = UrlEscapers.QUERY_ESCAPER.escape(parameterValue);
}
urlBuilder.appendQueryParameter(substitution.getUrlParameterName(), parameterValue);
}
}
}
}
} | UrlEscapers.QUERY_ESCAPER.escape("[]")); | public void setEncodedQueryParameters(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
if (swaggerMethodArguments == null) {
return;
}
for (QuerySubstitution substitution : querySubstitutions) {
final int parameterIndex = substitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[substitution.getMethodParameterIndex()];
if (substitution.mergeParameters() && methodArgument instanceof List) {
List<Object> methodArguments = (List<Object>) methodArgument;
for (Object argument : methodArguments) {
addSerializedQueryParameter(serializer, argument, substitution.shouldEncode(),
urlBuilder, substitution.getUrlParameterName());
}
} else {
addSerializedQueryParameter(serializer, methodArgument, substitution.shouldEncode(),
urlBuilder, substitution.getUrlParameterName());
}
}
}
} | class SwaggerMethodParser implements HttpResponseDecodeData {
private static final Pattern PATTERN_COLON_SLASH_SLASH = Pattern.compile(":
private final SerializerAdapter serializer;
private final String rawHost;
private final String fullyQualifiedMethodName;
private final HttpMethod httpMethod;
private final String relativePath;
private final List<Substitution> hostSubstitutions = new ArrayList<>();
private final List<Substitution> pathSubstitutions = new ArrayList<>();
private final List<QuerySubstitution> querySubstitutions = new ArrayList<>();
private final List<Substitution> formSubstitutions = new ArrayList<>();
private final List<Substitution> headerSubstitutions = new ArrayList<>();
private final HttpHeaders headers = new HttpHeaders();
private final Integer bodyContentMethodParameterIndex;
private final String bodyContentType;
private final Type bodyJavaType;
private final BitSet expectedStatusCodes;
private final Type returnType;
private final Type returnValueWireType;
private final UnexpectedResponseExceptionType[] unexpectedResponseExceptionTypes;
private Map<Integer, UnexpectedExceptionInformation> exceptionMapping;
private UnexpectedExceptionInformation defaultException;
/**
* Create a SwaggerMethodParser object using the provided fully qualified method name.
*
* @param swaggerMethod the Swagger method to parse.
* @param rawHost the raw host value from the @Host annotation. Before this can be used as the host value in an HTTP
* request, it must be processed through the possible host substitutions.
*/
SwaggerMethodParser(Method swaggerMethod, String rawHost) {
this(swaggerMethod, rawHost, JacksonAdapter.createDefaultSerializerAdapter());
}
SwaggerMethodParser(Method swaggerMethod, String rawHost, SerializerAdapter serializer) {
this.serializer = serializer;
this.rawHost = rawHost;
final Class<?> swaggerInterface = swaggerMethod.getDeclaringClass();
fullyQualifiedMethodName = swaggerInterface.getName() + "." + swaggerMethod.getName();
if (swaggerMethod.isAnnotationPresent(Get.class)) {
this.httpMethod = HttpMethod.GET;
this.relativePath = swaggerMethod.getAnnotation(Get.class).value();
} else if (swaggerMethod.isAnnotationPresent(Put.class)) {
this.httpMethod = HttpMethod.PUT;
this.relativePath = swaggerMethod.getAnnotation(Put.class).value();
} else if (swaggerMethod.isAnnotationPresent(Head.class)) {
this.httpMethod = HttpMethod.HEAD;
this.relativePath = swaggerMethod.getAnnotation(Head.class).value();
} else if (swaggerMethod.isAnnotationPresent(Delete.class)) {
this.httpMethod = HttpMethod.DELETE;
this.relativePath = swaggerMethod.getAnnotation(Delete.class).value();
} else if (swaggerMethod.isAnnotationPresent(Post.class)) {
this.httpMethod = HttpMethod.POST;
this.relativePath = swaggerMethod.getAnnotation(Post.class).value();
} else if (swaggerMethod.isAnnotationPresent(Patch.class)) {
this.httpMethod = HttpMethod.PATCH;
this.relativePath = swaggerMethod.getAnnotation(Patch.class).value();
} else {
throw new MissingRequiredAnnotationException(Arrays.asList(Get.class, Put.class, Head.class,
Delete.class, Post.class, Patch.class), swaggerMethod);
}
returnType = swaggerMethod.getGenericReturnType();
final ReturnValueWireType returnValueWireTypeAnnotation =
swaggerMethod.getAnnotation(ReturnValueWireType.class);
if (returnValueWireTypeAnnotation != null) {
Class<?> returnValueWireType = returnValueWireTypeAnnotation.value();
if (returnValueWireType == Base64Url.class
|| returnValueWireType == UnixTime.class
|| returnValueWireType == DateTimeRfc1123.class) {
this.returnValueWireType = returnValueWireType;
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, List.class)) {
this.returnValueWireType = returnValueWireType.getGenericInterfaces()[0];
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, Page.class)) {
this.returnValueWireType = returnValueWireType;
} else {
this.returnValueWireType = null;
}
} else {
this.returnValueWireType = null;
}
if (swaggerMethod.isAnnotationPresent(Headers.class)) {
final Headers headersAnnotation = swaggerMethod.getAnnotation(Headers.class);
final String[] headers = headersAnnotation.value();
for (final String header : headers) {
final int colonIndex = header.indexOf(":");
if (colonIndex >= 0) {
final String headerName = header.substring(0, colonIndex).trim();
if (!headerName.isEmpty()) {
final String headerValue = header.substring(colonIndex + 1).trim();
if (!headerValue.isEmpty()) {
if (headerValue.contains(",")) {
this.headers.set(headerName, Arrays.asList(headerValue.split(",")));
} else {
this.headers.set(headerName, headerValue);
}
}
}
}
}
}
final ExpectedResponses expectedResponses = swaggerMethod.getAnnotation(ExpectedResponses.class);
if (expectedResponses != null && expectedResponses.value().length > 0) {
expectedStatusCodes = new BitSet();
for (int code : expectedResponses.value()) {
expectedStatusCodes.set(code);
}
} else {
expectedStatusCodes = null;
}
unexpectedResponseExceptionTypes = swaggerMethod.getAnnotationsByType(UnexpectedResponseExceptionType.class);
Integer bodyContentMethodParameterIndex = null;
String bodyContentType = null;
Type bodyJavaType = null;
final Annotation[][] allParametersAnnotations = swaggerMethod.getParameterAnnotations();
for (int parameterIndex = 0; parameterIndex < allParametersAnnotations.length; ++parameterIndex) {
final Annotation[] parameterAnnotations = swaggerMethod.getParameterAnnotations()[parameterIndex];
for (final Annotation annotation : parameterAnnotations) {
final Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.equals(HostParam.class)) {
final HostParam hostParamAnnotation = (HostParam) annotation;
hostSubstitutions.add(new Substitution(hostParamAnnotation.value(), parameterIndex,
!hostParamAnnotation.encoded()));
} else if (annotationType.equals(PathParam.class)) {
final PathParam pathParamAnnotation = (PathParam) annotation;
pathSubstitutions.add(new Substitution(pathParamAnnotation.value(), parameterIndex,
!pathParamAnnotation.encoded()));
} else if (annotationType.equals(QueryParam.class)) {
final QueryParam queryParamAnnotation = (QueryParam) annotation;
querySubstitutions.add(new QuerySubstitution(queryParamAnnotation.value(), parameterIndex,
!queryParamAnnotation.encoded(), queryParamAnnotation.multipleQueryParams()));
} else if (annotationType.equals(HeaderParam.class)) {
final HeaderParam headerParamAnnotation = (HeaderParam) annotation;
headerSubstitutions.add(new Substitution(headerParamAnnotation.value(), parameterIndex,
false));
} else if (annotationType.equals(BodyParam.class)) {
final BodyParam bodyParamAnnotation = (BodyParam) annotation;
bodyContentMethodParameterIndex = parameterIndex;
bodyContentType = bodyParamAnnotation.value();
bodyJavaType = swaggerMethod.getGenericParameterTypes()[parameterIndex];
} else if (annotationType.equals(FormParam.class)) {
final FormParam formParamAnnotation = (FormParam) annotation;
formSubstitutions.add(new Substitution(formParamAnnotation.value(), parameterIndex,
!formParamAnnotation.encoded()));
bodyContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
bodyJavaType = String.class;
}
}
}
this.bodyContentMethodParameterIndex = bodyContentMethodParameterIndex;
this.bodyContentType = bodyContentType;
this.bodyJavaType = bodyJavaType;
}
/**
* Get the fully qualified method that was called to invoke this HTTP request.
*
* @return the fully qualified method that was called to invoke this HTTP request
*/
public String getFullyQualifiedMethodName() {
return fullyQualifiedMethodName;
}
/**
* Get the HTTP method that will be used to complete the Swagger method's request.
*
* @return the HTTP method that will be used to complete the Swagger method's request
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Sets the scheme and host to use for HTTP requests for this Swagger method.
*
* @param swaggerMethodArguments The arguments to use for scheme and host substitutions.
* @param urlBuilder The {@link UrlBuilder} that will have its scheme and host set.
*/
public void setSchemeAndHost(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments);
final String[] substitutedHostParts = PATTERN_COLON_SLASH_SLASH.split(substitutedHost);
if (substitutedHostParts.length >= 2) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHostParts[1]);
} else if (substitutedHostParts.length == 1) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHost);
} else {
urlBuilder.setHost(substitutedHost);
}
}
/**
* Get the path that will be used to complete the Swagger method's request.
*
* @param methodArguments the method arguments to use with the path substitutions
* @return the path value with its placeholders replaced by the matching substitutions
*/
public String setPath(Object[] methodArguments) {
return applySubstitutions(relativePath, pathSubstitutions, methodArguments);
}
/**
* Sets the encoded query parameters that have been added to this value based on the provided method arguments into
* the passed {@link UrlBuilder}.
*
* @param swaggerMethodArguments the arguments that will be used to create the query parameters' values
* @param urlBuilder The {@link UrlBuilder} where the encoded query parameters will be set.
*/
@SuppressWarnings("unchecked")
/**
* Sets the headers that have been added to this value based on the provided method arguments into the passed
* {@link HttpHeaders}.
*
* @param swaggerMethodArguments The arguments that will be used to create the headers' values.
* @param httpHeaders The {@link HttpHeaders} where the header values will be set.
*/
public void setHeaders(Object[] swaggerMethodArguments, HttpHeaders httpHeaders) {
for (HttpHeader header : headers) {
httpHeaders.set(header.getName(), header.getValuesList());
}
if (swaggerMethodArguments == null) {
return;
}
for (Substitution headerSubstitution : headerSubstitutions) {
final int parameterIndex = headerSubstitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[headerSubstitution.getMethodParameterIndex()];
if (methodArgument instanceof Map) {
@SuppressWarnings("unchecked") final Map<String, ?> headerCollection =
(Map<String, ?>) methodArgument;
final String headerCollectionPrefix = headerSubstitution.getUrlParameterName();
for (final Map.Entry<String, ?> headerCollectionEntry : headerCollection.entrySet()) {
final String headerName = headerCollectionPrefix + headerCollectionEntry.getKey();
final String headerValue = serialize(serializer, headerCollectionEntry.getValue());
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
} else {
final String headerName = headerSubstitution.getUrlParameterName();
final String headerValue = serialize(serializer, methodArgument);
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
}
}
}
/**
* Get the {@link Context} passed into the proxy method.
*
* @param swaggerMethodArguments the arguments passed to the proxy method
* @return the context, or {@link Context
*/
public Context setContext(Object[] swaggerMethodArguments) {
Context context = CoreUtils.findFirstOfType(swaggerMethodArguments, Context.class);
return (context != null) ? context : Context.NONE;
}
/**
* Get whether or not the provided response status code is one of the expected status codes for this Swagger
* method.
*
* 1. If the returned int[] is null, then all 2XX status codes are considered as success code.
* 2. If the returned int[] is not-null, only the codes in the array are considered as success code.
*
* @param statusCode the status code that was returned in the HTTP response
* @return whether or not the provided response status code is one of the expected status codes for this Swagger
* method
*/
@Override
public boolean isExpectedResponseStatusCode(final int statusCode) {
return expectedStatusCodes == null
? statusCode < 400
: expectedStatusCodes.get(statusCode);
}
/**
* Get the {@link UnexpectedExceptionInformation} that will be used to generate a RestException if the HTTP response
* status code is not one of the expected status codes.
*
* If an UnexpectedExceptionInformation is not found for the status code the default UnexpectedExceptionInformation
* will be returned.
*
* @param code Exception HTTP status code return from a REST API.
* @return the UnexpectedExceptionInformation to generate an exception to throw or return.
*/
@Override
public UnexpectedExceptionInformation getUnexpectedException(int code) {
if (exceptionMapping == null) {
exceptionMapping = processUnexpectedResponseExceptionTypes();
}
return exceptionMapping.getOrDefault(code, defaultException);
}
/**
* Get the object to be used as the value of the HTTP request.
*
* @param swaggerMethodArguments the method arguments to get the value object from
* @return the object that will be used as the body of the HTTP request
*/
public Object setBody(Object[] swaggerMethodArguments) {
Object result = null;
if (bodyContentMethodParameterIndex != null
&& swaggerMethodArguments != null
&& 0 <= bodyContentMethodParameterIndex
&& bodyContentMethodParameterIndex < swaggerMethodArguments.length) {
result = swaggerMethodArguments[bodyContentMethodParameterIndex];
}
if (!CoreUtils.isNullOrEmpty(formSubstitutions) && swaggerMethodArguments != null) {
result = formSubstitutions.stream()
.map(substitution -> serializeFormData(serializer, substitution.getUrlParameterName(),
swaggerMethodArguments[substitution.getMethodParameterIndex()], substitution.shouldEncode()))
.filter(Objects::nonNull)
.collect(Collectors.joining("&"));
}
return result;
}
/**
* Get the Content-Type of the body of this Swagger method.
*
* @return the Content-Type of the body of this Swagger method
*/
public String getBodyContentType() {
return bodyContentType;
}
/**
* Get the return type for the method that this object describes.
*
* @return the return type for the method that this object describes.
*/
@Override
public Type getReturnType() {
return returnType;
}
/**
* Get the type of the body parameter to this method, if present.
*
* @return the return type of the body parameter to this method
*/
public Type getBodyJavaType() {
return bodyJavaType;
}
/**
* Get the type that the return value will be send across the network as. If returnValueWireType is not null, then
* the raw HTTP response body will need to parsed to this type and then converted to the actual returnType.
*
* @return the type that the raw HTTP response body will be sent as
*/
@Override
public Type getReturnValueWireType() {
return returnValueWireType;
}
private static String serialize(SerializerAdapter serializer, Object value) {
if (value == null) {
return null;
}
if (value instanceof String) {
return (String) value;
} else {
return serializer.serializeRaw(value);
}
}
private static String serializeFormData(SerializerAdapter serializer, String key, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String encodedKey = UrlEscapers.FORM_ESCAPER.escape(key);
if (value instanceof List<?>) {
return ((List<?>) value).stream()
.map(element -> serializeAndEncodeFormValue(serializer, element, shouldEncode))
.filter(Objects::nonNull)
.map(formValue -> encodedKey + "=" + formValue)
.collect(Collectors.joining("&"));
} else {
return encodedKey + "=" + serializeAndEncodeFormValue(serializer, value, shouldEncode);
}
}
private static String serializeAndEncodeFormValue(SerializerAdapter serializer, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String serializedValue = serializer.serializeRaw(value);
return shouldEncode ? UrlEscapers.FORM_ESCAPER.escape(serializedValue) : serializedValue;
}
private String applySubstitutions(String originalValue, Iterable<Substitution> substitutions,
Object[] methodArguments) {
String result = originalValue;
if (methodArguments != null) {
for (Substitution substitution : substitutions) {
final int substitutionParameterIndex = substitution.getMethodParameterIndex();
if (0 <= substitutionParameterIndex && substitutionParameterIndex < methodArguments.length) {
final Object methodArgument = methodArguments[substitutionParameterIndex];
String substitutionValue = serialize(serializer, methodArgument);
if (substitutionValue != null && !substitutionValue.isEmpty() && substitution.shouldEncode()) {
substitutionValue = UrlEscapers.PATH_ESCAPER.escape(substitutionValue);
}
if (substitutionValue == null) {
substitutionValue = "";
}
result = result.replace("{" + substitution.getUrlParameterName() + "}", substitutionValue);
}
}
}
return result;
}
private Map<Integer, UnexpectedExceptionInformation> processUnexpectedResponseExceptionTypes() {
HashMap<Integer, UnexpectedExceptionInformation> exceptionHashMap = new HashMap<>();
for (UnexpectedResponseExceptionType exceptionAnnotation : unexpectedResponseExceptionTypes) {
UnexpectedExceptionInformation exception = new UnexpectedExceptionInformation(exceptionAnnotation.value());
if (exceptionAnnotation.code().length == 0) {
defaultException = exception;
} else {
for (int statusCode : exceptionAnnotation.code()) {
exceptionHashMap.put(statusCode, exception);
}
}
}
if (defaultException == null) {
defaultException = new UnexpectedExceptionInformation(HttpResponseException.class);
}
return exceptionHashMap;
}
} | class SwaggerMethodParser implements HttpResponseDecodeData {
private static final Pattern PATTERN_COLON_SLASH_SLASH = Pattern.compile(":
private final SerializerAdapter serializer;
private final String rawHost;
private final String fullyQualifiedMethodName;
private final HttpMethod httpMethod;
private final String relativePath;
private final List<Substitution> hostSubstitutions = new ArrayList<>();
private final List<Substitution> pathSubstitutions = new ArrayList<>();
private final List<QuerySubstitution> querySubstitutions = new ArrayList<>();
private final List<Substitution> formSubstitutions = new ArrayList<>();
private final List<Substitution> headerSubstitutions = new ArrayList<>();
private final HttpHeaders headers = new HttpHeaders();
private final Integer bodyContentMethodParameterIndex;
private final String bodyContentType;
private final Type bodyJavaType;
private final BitSet expectedStatusCodes;
private final Type returnType;
private final Type returnValueWireType;
private final UnexpectedResponseExceptionType[] unexpectedResponseExceptionTypes;
private Map<Integer, UnexpectedExceptionInformation> exceptionMapping;
private UnexpectedExceptionInformation defaultException;
/**
* Create a SwaggerMethodParser object using the provided fully qualified method name.
*
* @param swaggerMethod the Swagger method to parse.
* @param rawHost the raw host value from the @Host annotation. Before this can be used as the host value in an HTTP
* request, it must be processed through the possible host substitutions.
*/
SwaggerMethodParser(Method swaggerMethod, String rawHost) {
this(swaggerMethod, rawHost, JacksonAdapter.createDefaultSerializerAdapter());
}
SwaggerMethodParser(Method swaggerMethod, String rawHost, SerializerAdapter serializer) {
this.serializer = serializer;
this.rawHost = rawHost;
final Class<?> swaggerInterface = swaggerMethod.getDeclaringClass();
fullyQualifiedMethodName = swaggerInterface.getName() + "." + swaggerMethod.getName();
if (swaggerMethod.isAnnotationPresent(Get.class)) {
this.httpMethod = HttpMethod.GET;
this.relativePath = swaggerMethod.getAnnotation(Get.class).value();
} else if (swaggerMethod.isAnnotationPresent(Put.class)) {
this.httpMethod = HttpMethod.PUT;
this.relativePath = swaggerMethod.getAnnotation(Put.class).value();
} else if (swaggerMethod.isAnnotationPresent(Head.class)) {
this.httpMethod = HttpMethod.HEAD;
this.relativePath = swaggerMethod.getAnnotation(Head.class).value();
} else if (swaggerMethod.isAnnotationPresent(Delete.class)) {
this.httpMethod = HttpMethod.DELETE;
this.relativePath = swaggerMethod.getAnnotation(Delete.class).value();
} else if (swaggerMethod.isAnnotationPresent(Post.class)) {
this.httpMethod = HttpMethod.POST;
this.relativePath = swaggerMethod.getAnnotation(Post.class).value();
} else if (swaggerMethod.isAnnotationPresent(Patch.class)) {
this.httpMethod = HttpMethod.PATCH;
this.relativePath = swaggerMethod.getAnnotation(Patch.class).value();
} else {
throw new MissingRequiredAnnotationException(Arrays.asList(Get.class, Put.class, Head.class,
Delete.class, Post.class, Patch.class), swaggerMethod);
}
returnType = swaggerMethod.getGenericReturnType();
final ReturnValueWireType returnValueWireTypeAnnotation =
swaggerMethod.getAnnotation(ReturnValueWireType.class);
if (returnValueWireTypeAnnotation != null) {
Class<?> returnValueWireType = returnValueWireTypeAnnotation.value();
if (returnValueWireType == Base64Url.class
|| returnValueWireType == UnixTime.class
|| returnValueWireType == DateTimeRfc1123.class) {
this.returnValueWireType = returnValueWireType;
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, List.class)) {
this.returnValueWireType = returnValueWireType.getGenericInterfaces()[0];
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, Page.class)) {
this.returnValueWireType = returnValueWireType;
} else {
this.returnValueWireType = null;
}
} else {
this.returnValueWireType = null;
}
if (swaggerMethod.isAnnotationPresent(Headers.class)) {
final Headers headersAnnotation = swaggerMethod.getAnnotation(Headers.class);
final String[] headers = headersAnnotation.value();
for (final String header : headers) {
final int colonIndex = header.indexOf(":");
if (colonIndex >= 0) {
final String headerName = header.substring(0, colonIndex).trim();
if (!headerName.isEmpty()) {
final String headerValue = header.substring(colonIndex + 1).trim();
if (!headerValue.isEmpty()) {
if (headerValue.contains(",")) {
this.headers.set(headerName, Arrays.asList(headerValue.split(",")));
} else {
this.headers.set(headerName, headerValue);
}
}
}
}
}
}
final ExpectedResponses expectedResponses = swaggerMethod.getAnnotation(ExpectedResponses.class);
if (expectedResponses != null && expectedResponses.value().length > 0) {
expectedStatusCodes = new BitSet();
for (int code : expectedResponses.value()) {
expectedStatusCodes.set(code);
}
} else {
expectedStatusCodes = null;
}
unexpectedResponseExceptionTypes = swaggerMethod.getAnnotationsByType(UnexpectedResponseExceptionType.class);
Integer bodyContentMethodParameterIndex = null;
String bodyContentType = null;
Type bodyJavaType = null;
final Annotation[][] allParametersAnnotations = swaggerMethod.getParameterAnnotations();
for (int parameterIndex = 0; parameterIndex < allParametersAnnotations.length; ++parameterIndex) {
final Annotation[] parameterAnnotations = swaggerMethod.getParameterAnnotations()[parameterIndex];
for (final Annotation annotation : parameterAnnotations) {
final Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.equals(HostParam.class)) {
final HostParam hostParamAnnotation = (HostParam) annotation;
hostSubstitutions.add(new Substitution(hostParamAnnotation.value(), parameterIndex,
!hostParamAnnotation.encoded()));
} else if (annotationType.equals(PathParam.class)) {
final PathParam pathParamAnnotation = (PathParam) annotation;
pathSubstitutions.add(new Substitution(pathParamAnnotation.value(), parameterIndex,
!pathParamAnnotation.encoded()));
} else if (annotationType.equals(QueryParam.class)) {
final QueryParam queryParamAnnotation = (QueryParam) annotation;
querySubstitutions.add(new QuerySubstitution(queryParamAnnotation.value(), parameterIndex,
!queryParamAnnotation.encoded(), queryParamAnnotation.multipleQueryParams()));
} else if (annotationType.equals(HeaderParam.class)) {
final HeaderParam headerParamAnnotation = (HeaderParam) annotation;
headerSubstitutions.add(new Substitution(headerParamAnnotation.value(), parameterIndex,
false));
} else if (annotationType.equals(BodyParam.class)) {
final BodyParam bodyParamAnnotation = (BodyParam) annotation;
bodyContentMethodParameterIndex = parameterIndex;
bodyContentType = bodyParamAnnotation.value();
bodyJavaType = swaggerMethod.getGenericParameterTypes()[parameterIndex];
} else if (annotationType.equals(FormParam.class)) {
final FormParam formParamAnnotation = (FormParam) annotation;
formSubstitutions.add(new Substitution(formParamAnnotation.value(), parameterIndex,
!formParamAnnotation.encoded()));
bodyContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
bodyJavaType = String.class;
}
}
}
this.bodyContentMethodParameterIndex = bodyContentMethodParameterIndex;
this.bodyContentType = bodyContentType;
this.bodyJavaType = bodyJavaType;
}
/**
* Get the fully qualified method that was called to invoke this HTTP request.
*
* @return the fully qualified method that was called to invoke this HTTP request
*/
public String getFullyQualifiedMethodName() {
return fullyQualifiedMethodName;
}
/**
* Get the HTTP method that will be used to complete the Swagger method's request.
*
* @return the HTTP method that will be used to complete the Swagger method's request
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Sets the scheme and host to use for HTTP requests for this Swagger method.
*
* @param swaggerMethodArguments The arguments to use for scheme and host substitutions.
* @param urlBuilder The {@link UrlBuilder} that will have its scheme and host set.
*/
public void setSchemeAndHost(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments);
final String[] substitutedHostParts = PATTERN_COLON_SLASH_SLASH.split(substitutedHost);
if (substitutedHostParts.length >= 2) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHostParts[1]);
} else if (substitutedHostParts.length == 1) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHost);
} else {
urlBuilder.setHost(substitutedHost);
}
}
/**
* Get the path that will be used to complete the Swagger method's request.
*
* @param methodArguments the method arguments to use with the path substitutions
* @return the path value with its placeholders replaced by the matching substitutions
*/
public String setPath(Object[] methodArguments) {
return applySubstitutions(relativePath, pathSubstitutions, methodArguments);
}
/**
* Sets the encoded query parameters that have been added to this value based on the provided method arguments into
* the passed {@link UrlBuilder}.
*
* @param swaggerMethodArguments the arguments that will be used to create the query parameters' values
* @param urlBuilder The {@link UrlBuilder} where the encoded query parameters will be set.
*/
@SuppressWarnings("unchecked")
/**
* Sets the headers that have been added to this value based on the provided method arguments into the passed
* {@link HttpHeaders}.
*
* @param swaggerMethodArguments The arguments that will be used to create the headers' values.
* @param httpHeaders The {@link HttpHeaders} where the header values will be set.
*/
public void setHeaders(Object[] swaggerMethodArguments, HttpHeaders httpHeaders) {
for (HttpHeader header : headers) {
httpHeaders.set(header.getName(), header.getValuesList());
}
if (swaggerMethodArguments == null) {
return;
}
for (Substitution headerSubstitution : headerSubstitutions) {
final int parameterIndex = headerSubstitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[headerSubstitution.getMethodParameterIndex()];
if (methodArgument instanceof Map) {
@SuppressWarnings("unchecked") final Map<String, ?> headerCollection =
(Map<String, ?>) methodArgument;
final String headerCollectionPrefix = headerSubstitution.getUrlParameterName();
for (final Map.Entry<String, ?> headerCollectionEntry : headerCollection.entrySet()) {
final String headerName = headerCollectionPrefix + headerCollectionEntry.getKey();
final String headerValue = serialize(serializer, headerCollectionEntry.getValue());
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
} else {
final String headerName = headerSubstitution.getUrlParameterName();
final String headerValue = serialize(serializer, methodArgument);
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
}
}
}
/**
* Get the {@link Context} passed into the proxy method.
*
* @param swaggerMethodArguments the arguments passed to the proxy method
* @return the context, or {@link Context
*/
public Context setContext(Object[] swaggerMethodArguments) {
Context context = CoreUtils.findFirstOfType(swaggerMethodArguments, Context.class);
return (context != null) ? context : Context.NONE;
}
/**
* Get whether or not the provided response status code is one of the expected status codes for this Swagger
* method.
*
* 1. If the returned int[] is null, then all 2XX status codes are considered as success code.
* 2. If the returned int[] is not-null, only the codes in the array are considered as success code.
*
* @param statusCode the status code that was returned in the HTTP response
* @return whether or not the provided response status code is one of the expected status codes for this Swagger
* method
*/
@Override
public boolean isExpectedResponseStatusCode(final int statusCode) {
return expectedStatusCodes == null
? statusCode < 400
: expectedStatusCodes.get(statusCode);
}
/**
* Get the {@link UnexpectedExceptionInformation} that will be used to generate a RestException if the HTTP response
* status code is not one of the expected status codes.
*
* If an UnexpectedExceptionInformation is not found for the status code the default UnexpectedExceptionInformation
* will be returned.
*
* @param code Exception HTTP status code return from a REST API.
* @return the UnexpectedExceptionInformation to generate an exception to throw or return.
*/
@Override
public UnexpectedExceptionInformation getUnexpectedException(int code) {
if (exceptionMapping == null) {
exceptionMapping = processUnexpectedResponseExceptionTypes();
}
return exceptionMapping.getOrDefault(code, defaultException);
}
/**
* Get the object to be used as the value of the HTTP request.
*
* @param swaggerMethodArguments the method arguments to get the value object from
* @return the object that will be used as the body of the HTTP request
*/
public Object setBody(Object[] swaggerMethodArguments) {
Object result = null;
if (bodyContentMethodParameterIndex != null
&& swaggerMethodArguments != null
&& 0 <= bodyContentMethodParameterIndex
&& bodyContentMethodParameterIndex < swaggerMethodArguments.length) {
result = swaggerMethodArguments[bodyContentMethodParameterIndex];
}
if (!CoreUtils.isNullOrEmpty(formSubstitutions) && swaggerMethodArguments != null) {
result = formSubstitutions.stream()
.map(substitution -> serializeFormData(serializer, substitution.getUrlParameterName(),
swaggerMethodArguments[substitution.getMethodParameterIndex()], substitution.shouldEncode()))
.filter(Objects::nonNull)
.collect(Collectors.joining("&"));
}
return result;
}
/**
* Get the Content-Type of the body of this Swagger method.
*
* @return the Content-Type of the body of this Swagger method
*/
public String getBodyContentType() {
return bodyContentType;
}
/**
* Get the return type for the method that this object describes.
*
* @return the return type for the method that this object describes.
*/
@Override
public Type getReturnType() {
return returnType;
}
/**
* Get the type of the body parameter to this method, if present.
*
* @return the return type of the body parameter to this method
*/
public Type getBodyJavaType() {
return bodyJavaType;
}
/**
* Get the type that the return value will be send across the network as. If returnValueWireType is not null, then
* the raw HTTP response body will need to parsed to this type and then converted to the actual returnType.
*
* @return the type that the raw HTTP response body will be sent as
*/
@Override
public Type getReturnValueWireType() {
return returnValueWireType;
}
private static void addSerializedQueryParameter(SerializerAdapter adapter, Object value, boolean shouldEncode,
UrlBuilder urlBuilder, String parameterName) {
String parameterValue = serialize(adapter, value);
if (parameterValue != null) {
if (shouldEncode) {
parameterValue = UrlEscapers.QUERY_ESCAPER.escape(parameterValue);
}
urlBuilder.addQueryParameter(parameterName, parameterValue);
}
}
private static String serialize(SerializerAdapter serializer, Object value) {
if (value == null) {
return null;
}
if (value instanceof String) {
return (String) value;
} else {
return serializer.serializeRaw(value);
}
}
private static String serializeFormData(SerializerAdapter serializer, String key, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String encodedKey = UrlEscapers.FORM_ESCAPER.escape(key);
if (value instanceof List<?>) {
return ((List<?>) value).stream()
.map(element -> serializeAndEncodeFormValue(serializer, element, shouldEncode))
.filter(Objects::nonNull)
.map(formValue -> encodedKey + "=" + formValue)
.collect(Collectors.joining("&"));
} else {
return encodedKey + "=" + serializeAndEncodeFormValue(serializer, value, shouldEncode);
}
}
private static String serializeAndEncodeFormValue(SerializerAdapter serializer, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String serializedValue = serializer.serializeRaw(value);
return shouldEncode ? UrlEscapers.FORM_ESCAPER.escape(serializedValue) : serializedValue;
}
private String applySubstitutions(String originalValue, Iterable<Substitution> substitutions,
Object[] methodArguments) {
String result = originalValue;
if (methodArguments != null) {
for (Substitution substitution : substitutions) {
final int substitutionParameterIndex = substitution.getMethodParameterIndex();
if (0 <= substitutionParameterIndex && substitutionParameterIndex < methodArguments.length) {
final Object methodArgument = methodArguments[substitutionParameterIndex];
String substitutionValue = serialize(serializer, methodArgument);
if (substitutionValue != null && !substitutionValue.isEmpty() && substitution.shouldEncode()) {
substitutionValue = UrlEscapers.PATH_ESCAPER.escape(substitutionValue);
}
if (substitutionValue == null) {
substitutionValue = "";
}
result = result.replace("{" + substitution.getUrlParameterName() + "}", substitutionValue);
}
}
}
return result;
}
private Map<Integer, UnexpectedExceptionInformation> processUnexpectedResponseExceptionTypes() {
HashMap<Integer, UnexpectedExceptionInformation> exceptionHashMap = new HashMap<>();
for (UnexpectedResponseExceptionType exceptionAnnotation : unexpectedResponseExceptionTypes) {
UnexpectedExceptionInformation exception = new UnexpectedExceptionInformation(exceptionAnnotation.value());
if (exceptionAnnotation.code().length == 0) {
defaultException = exception;
} else {
for (int statusCode : exceptionAnnotation.code()) {
exceptionHashMap.put(statusCode, exception);
}
}
}
if (defaultException == null) {
defaultException = new UnexpectedExceptionInformation(HttpResponseException.class);
}
return exceptionHashMap;
}
} |
From a perf standpoint I would switch these two conditions of the `if` statement to run the cheap boolean check first and only if it is true run the `instanceof` check. I would also suggest making this code more performant by removing the intermediate `methodArguments` list and just having two code paths in these if / else code block. | public void setEncodedQueryParameters(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
if (swaggerMethodArguments == null) {
return;
}
for (QuerySubstitution substitution : querySubstitutions) {
final int parameterIndex = substitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[substitution.getMethodParameterIndex()];
List<Object> methodArguments = new ArrayList<Object>();
if (methodArgument instanceof List && substitution.shouldMergeQueryParams()) {
methodArguments.addAll((List<Object>) methodArgument);
} else {
methodArguments.add(methodArgument);
}
for (Object methodArgumentUnconverted : methodArguments) {
String parameterValue = serialize(serializer, methodArgumentUnconverted);
if (parameterValue != null) {
if (substitution.shouldEncode()) {
parameterValue = UrlEscapers.QUERY_ESCAPER.escape(parameterValue);
}
urlBuilder.appendQueryParameter(substitution.getUrlParameterName(), parameterValue);
}
}
}
}
} | if (methodArgument instanceof List && substitution.shouldMergeQueryParams()) { | public void setEncodedQueryParameters(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
if (swaggerMethodArguments == null) {
return;
}
for (QuerySubstitution substitution : querySubstitutions) {
final int parameterIndex = substitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[substitution.getMethodParameterIndex()];
if (substitution.mergeParameters() && methodArgument instanceof List) {
List<Object> methodArguments = (List<Object>) methodArgument;
for (Object argument : methodArguments) {
addSerializedQueryParameter(serializer, argument, substitution.shouldEncode(),
urlBuilder, substitution.getUrlParameterName());
}
} else {
addSerializedQueryParameter(serializer, methodArgument, substitution.shouldEncode(),
urlBuilder, substitution.getUrlParameterName());
}
}
}
} | class SwaggerMethodParser implements HttpResponseDecodeData {
private static final Pattern PATTERN_COLON_SLASH_SLASH = Pattern.compile(":
private final SerializerAdapter serializer;
private final String rawHost;
private final String fullyQualifiedMethodName;
private final HttpMethod httpMethod;
private final String relativePath;
private final List<Substitution> hostSubstitutions = new ArrayList<>();
private final List<Substitution> pathSubstitutions = new ArrayList<>();
private final List<QuerySubstitution> querySubstitutions = new ArrayList<>();
private final List<Substitution> formSubstitutions = new ArrayList<>();
private final List<Substitution> headerSubstitutions = new ArrayList<>();
private final HttpHeaders headers = new HttpHeaders();
private final Integer bodyContentMethodParameterIndex;
private final String bodyContentType;
private final Type bodyJavaType;
private final BitSet expectedStatusCodes;
private final Type returnType;
private final Type returnValueWireType;
private final UnexpectedResponseExceptionType[] unexpectedResponseExceptionTypes;
private Map<Integer, UnexpectedExceptionInformation> exceptionMapping;
private UnexpectedExceptionInformation defaultException;
/**
* Create a SwaggerMethodParser object using the provided fully qualified method name.
*
* @param swaggerMethod the Swagger method to parse.
* @param rawHost the raw host value from the @Host annotation. Before this can be used as the host value in an HTTP
* request, it must be processed through the possible host substitutions.
*/
SwaggerMethodParser(Method swaggerMethod, String rawHost) {
this(swaggerMethod, rawHost, JacksonAdapter.createDefaultSerializerAdapter());
}
SwaggerMethodParser(Method swaggerMethod, String rawHost, SerializerAdapter serializer) {
this.serializer = serializer;
this.rawHost = rawHost;
final Class<?> swaggerInterface = swaggerMethod.getDeclaringClass();
fullyQualifiedMethodName = swaggerInterface.getName() + "." + swaggerMethod.getName();
if (swaggerMethod.isAnnotationPresent(Get.class)) {
this.httpMethod = HttpMethod.GET;
this.relativePath = swaggerMethod.getAnnotation(Get.class).value();
} else if (swaggerMethod.isAnnotationPresent(Put.class)) {
this.httpMethod = HttpMethod.PUT;
this.relativePath = swaggerMethod.getAnnotation(Put.class).value();
} else if (swaggerMethod.isAnnotationPresent(Head.class)) {
this.httpMethod = HttpMethod.HEAD;
this.relativePath = swaggerMethod.getAnnotation(Head.class).value();
} else if (swaggerMethod.isAnnotationPresent(Delete.class)) {
this.httpMethod = HttpMethod.DELETE;
this.relativePath = swaggerMethod.getAnnotation(Delete.class).value();
} else if (swaggerMethod.isAnnotationPresent(Post.class)) {
this.httpMethod = HttpMethod.POST;
this.relativePath = swaggerMethod.getAnnotation(Post.class).value();
} else if (swaggerMethod.isAnnotationPresent(Patch.class)) {
this.httpMethod = HttpMethod.PATCH;
this.relativePath = swaggerMethod.getAnnotation(Patch.class).value();
} else {
throw new MissingRequiredAnnotationException(Arrays.asList(Get.class, Put.class, Head.class,
Delete.class, Post.class, Patch.class), swaggerMethod);
}
returnType = swaggerMethod.getGenericReturnType();
final ReturnValueWireType returnValueWireTypeAnnotation =
swaggerMethod.getAnnotation(ReturnValueWireType.class);
if (returnValueWireTypeAnnotation != null) {
Class<?> returnValueWireType = returnValueWireTypeAnnotation.value();
if (returnValueWireType == Base64Url.class
|| returnValueWireType == UnixTime.class
|| returnValueWireType == DateTimeRfc1123.class) {
this.returnValueWireType = returnValueWireType;
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, List.class)) {
this.returnValueWireType = returnValueWireType.getGenericInterfaces()[0];
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, Page.class)) {
this.returnValueWireType = returnValueWireType;
} else {
this.returnValueWireType = null;
}
} else {
this.returnValueWireType = null;
}
if (swaggerMethod.isAnnotationPresent(Headers.class)) {
final Headers headersAnnotation = swaggerMethod.getAnnotation(Headers.class);
final String[] headers = headersAnnotation.value();
for (final String header : headers) {
final int colonIndex = header.indexOf(":");
if (colonIndex >= 0) {
final String headerName = header.substring(0, colonIndex).trim();
if (!headerName.isEmpty()) {
final String headerValue = header.substring(colonIndex + 1).trim();
if (!headerValue.isEmpty()) {
if (headerValue.contains(",")) {
this.headers.set(headerName, Arrays.asList(headerValue.split(",")));
} else {
this.headers.set(headerName, headerValue);
}
}
}
}
}
}
final ExpectedResponses expectedResponses = swaggerMethod.getAnnotation(ExpectedResponses.class);
if (expectedResponses != null && expectedResponses.value().length > 0) {
expectedStatusCodes = new BitSet();
for (int code : expectedResponses.value()) {
expectedStatusCodes.set(code);
}
} else {
expectedStatusCodes = null;
}
unexpectedResponseExceptionTypes = swaggerMethod.getAnnotationsByType(UnexpectedResponseExceptionType.class);
Integer bodyContentMethodParameterIndex = null;
String bodyContentType = null;
Type bodyJavaType = null;
final Annotation[][] allParametersAnnotations = swaggerMethod.getParameterAnnotations();
for (int parameterIndex = 0; parameterIndex < allParametersAnnotations.length; ++parameterIndex) {
final Annotation[] parameterAnnotations = swaggerMethod.getParameterAnnotations()[parameterIndex];
for (final Annotation annotation : parameterAnnotations) {
final Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.equals(HostParam.class)) {
final HostParam hostParamAnnotation = (HostParam) annotation;
hostSubstitutions.add(new Substitution(hostParamAnnotation.value(), parameterIndex,
!hostParamAnnotation.encoded()));
} else if (annotationType.equals(PathParam.class)) {
final PathParam pathParamAnnotation = (PathParam) annotation;
pathSubstitutions.add(new Substitution(pathParamAnnotation.value(), parameterIndex,
!pathParamAnnotation.encoded()));
} else if (annotationType.equals(QueryParam.class)) {
final QueryParam queryParamAnnotation = (QueryParam) annotation;
querySubstitutions.add(new QuerySubstitution(queryParamAnnotation.value(), parameterIndex,
!queryParamAnnotation.encoded(), queryParamAnnotation.multipleQueryParams()));
} else if (annotationType.equals(HeaderParam.class)) {
final HeaderParam headerParamAnnotation = (HeaderParam) annotation;
headerSubstitutions.add(new Substitution(headerParamAnnotation.value(), parameterIndex,
false));
} else if (annotationType.equals(BodyParam.class)) {
final BodyParam bodyParamAnnotation = (BodyParam) annotation;
bodyContentMethodParameterIndex = parameterIndex;
bodyContentType = bodyParamAnnotation.value();
bodyJavaType = swaggerMethod.getGenericParameterTypes()[parameterIndex];
} else if (annotationType.equals(FormParam.class)) {
final FormParam formParamAnnotation = (FormParam) annotation;
formSubstitutions.add(new Substitution(formParamAnnotation.value(), parameterIndex,
!formParamAnnotation.encoded()));
bodyContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
bodyJavaType = String.class;
}
}
}
this.bodyContentMethodParameterIndex = bodyContentMethodParameterIndex;
this.bodyContentType = bodyContentType;
this.bodyJavaType = bodyJavaType;
}
/**
* Get the fully qualified method that was called to invoke this HTTP request.
*
* @return the fully qualified method that was called to invoke this HTTP request
*/
public String getFullyQualifiedMethodName() {
return fullyQualifiedMethodName;
}
/**
* Get the HTTP method that will be used to complete the Swagger method's request.
*
* @return the HTTP method that will be used to complete the Swagger method's request
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Sets the scheme and host to use for HTTP requests for this Swagger method.
*
* @param swaggerMethodArguments The arguments to use for scheme and host substitutions.
* @param urlBuilder The {@link UrlBuilder} that will have its scheme and host set.
*/
public void setSchemeAndHost(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments);
final String[] substitutedHostParts = PATTERN_COLON_SLASH_SLASH.split(substitutedHost);
if (substitutedHostParts.length >= 2) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHostParts[1]);
} else if (substitutedHostParts.length == 1) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHost);
} else {
urlBuilder.setHost(substitutedHost);
}
}
/**
* Get the path that will be used to complete the Swagger method's request.
*
* @param methodArguments the method arguments to use with the path substitutions
* @return the path value with its placeholders replaced by the matching substitutions
*/
public String setPath(Object[] methodArguments) {
return applySubstitutions(relativePath, pathSubstitutions, methodArguments);
}
/**
* Sets the encoded query parameters that have been added to this value based on the provided method arguments into
* the passed {@link UrlBuilder}.
*
* @param swaggerMethodArguments the arguments that will be used to create the query parameters' values
* @param urlBuilder The {@link UrlBuilder} where the encoded query parameters will be set.
*/
@SuppressWarnings("unchecked")
/**
* Sets the headers that have been added to this value based on the provided method arguments into the passed
* {@link HttpHeaders}.
*
* @param swaggerMethodArguments The arguments that will be used to create the headers' values.
* @param httpHeaders The {@link HttpHeaders} where the header values will be set.
*/
public void setHeaders(Object[] swaggerMethodArguments, HttpHeaders httpHeaders) {
for (HttpHeader header : headers) {
httpHeaders.set(header.getName(), header.getValuesList());
}
if (swaggerMethodArguments == null) {
return;
}
for (Substitution headerSubstitution : headerSubstitutions) {
final int parameterIndex = headerSubstitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[headerSubstitution.getMethodParameterIndex()];
if (methodArgument instanceof Map) {
@SuppressWarnings("unchecked") final Map<String, ?> headerCollection =
(Map<String, ?>) methodArgument;
final String headerCollectionPrefix = headerSubstitution.getUrlParameterName();
for (final Map.Entry<String, ?> headerCollectionEntry : headerCollection.entrySet()) {
final String headerName = headerCollectionPrefix + headerCollectionEntry.getKey();
final String headerValue = serialize(serializer, headerCollectionEntry.getValue());
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
} else {
final String headerName = headerSubstitution.getUrlParameterName();
final String headerValue = serialize(serializer, methodArgument);
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
}
}
}
/**
* Get the {@link Context} passed into the proxy method.
*
* @param swaggerMethodArguments the arguments passed to the proxy method
* @return the context, or {@link Context
*/
public Context setContext(Object[] swaggerMethodArguments) {
Context context = CoreUtils.findFirstOfType(swaggerMethodArguments, Context.class);
return (context != null) ? context : Context.NONE;
}
/**
* Get whether or not the provided response status code is one of the expected status codes for this Swagger
* method.
*
* 1. If the returned int[] is null, then all 2XX status codes are considered as success code.
* 2. If the returned int[] is not-null, only the codes in the array are considered as success code.
*
* @param statusCode the status code that was returned in the HTTP response
* @return whether or not the provided response status code is one of the expected status codes for this Swagger
* method
*/
@Override
public boolean isExpectedResponseStatusCode(final int statusCode) {
return expectedStatusCodes == null
? statusCode < 400
: expectedStatusCodes.get(statusCode);
}
/**
* Get the {@link UnexpectedExceptionInformation} that will be used to generate a RestException if the HTTP response
* status code is not one of the expected status codes.
*
* If an UnexpectedExceptionInformation is not found for the status code the default UnexpectedExceptionInformation
* will be returned.
*
* @param code Exception HTTP status code return from a REST API.
* @return the UnexpectedExceptionInformation to generate an exception to throw or return.
*/
@Override
public UnexpectedExceptionInformation getUnexpectedException(int code) {
if (exceptionMapping == null) {
exceptionMapping = processUnexpectedResponseExceptionTypes();
}
return exceptionMapping.getOrDefault(code, defaultException);
}
/**
* Get the object to be used as the value of the HTTP request.
*
* @param swaggerMethodArguments the method arguments to get the value object from
* @return the object that will be used as the body of the HTTP request
*/
public Object setBody(Object[] swaggerMethodArguments) {
Object result = null;
if (bodyContentMethodParameterIndex != null
&& swaggerMethodArguments != null
&& 0 <= bodyContentMethodParameterIndex
&& bodyContentMethodParameterIndex < swaggerMethodArguments.length) {
result = swaggerMethodArguments[bodyContentMethodParameterIndex];
}
if (!CoreUtils.isNullOrEmpty(formSubstitutions) && swaggerMethodArguments != null) {
result = formSubstitutions.stream()
.map(substitution -> serializeFormData(serializer, substitution.getUrlParameterName(),
swaggerMethodArguments[substitution.getMethodParameterIndex()], substitution.shouldEncode()))
.filter(Objects::nonNull)
.collect(Collectors.joining("&"));
}
return result;
}
/**
* Get the Content-Type of the body of this Swagger method.
*
* @return the Content-Type of the body of this Swagger method
*/
public String getBodyContentType() {
return bodyContentType;
}
/**
* Get the return type for the method that this object describes.
*
* @return the return type for the method that this object describes.
*/
@Override
public Type getReturnType() {
return returnType;
}
/**
* Get the type of the body parameter to this method, if present.
*
* @return the return type of the body parameter to this method
*/
public Type getBodyJavaType() {
return bodyJavaType;
}
/**
* Get the type that the return value will be send across the network as. If returnValueWireType is not null, then
* the raw HTTP response body will need to parsed to this type and then converted to the actual returnType.
*
* @return the type that the raw HTTP response body will be sent as
*/
@Override
public Type getReturnValueWireType() {
return returnValueWireType;
}
private static String serialize(SerializerAdapter serializer, Object value) {
if (value == null) {
return null;
}
if (value instanceof String) {
return (String) value;
} else {
return serializer.serializeRaw(value);
}
}
private static String serializeFormData(SerializerAdapter serializer, String key, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String encodedKey = UrlEscapers.FORM_ESCAPER.escape(key);
if (value instanceof List<?>) {
return ((List<?>) value).stream()
.map(element -> serializeAndEncodeFormValue(serializer, element, shouldEncode))
.filter(Objects::nonNull)
.map(formValue -> encodedKey + "=" + formValue)
.collect(Collectors.joining("&"));
} else {
return encodedKey + "=" + serializeAndEncodeFormValue(serializer, value, shouldEncode);
}
}
private static String serializeAndEncodeFormValue(SerializerAdapter serializer, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String serializedValue = serializer.serializeRaw(value);
return shouldEncode ? UrlEscapers.FORM_ESCAPER.escape(serializedValue) : serializedValue;
}
private String applySubstitutions(String originalValue, Iterable<Substitution> substitutions,
Object[] methodArguments) {
String result = originalValue;
if (methodArguments != null) {
for (Substitution substitution : substitutions) {
final int substitutionParameterIndex = substitution.getMethodParameterIndex();
if (0 <= substitutionParameterIndex && substitutionParameterIndex < methodArguments.length) {
final Object methodArgument = methodArguments[substitutionParameterIndex];
String substitutionValue = serialize(serializer, methodArgument);
if (substitutionValue != null && !substitutionValue.isEmpty() && substitution.shouldEncode()) {
substitutionValue = UrlEscapers.PATH_ESCAPER.escape(substitutionValue);
}
if (substitutionValue == null) {
substitutionValue = "";
}
result = result.replace("{" + substitution.getUrlParameterName() + "}", substitutionValue);
}
}
}
return result;
}
private Map<Integer, UnexpectedExceptionInformation> processUnexpectedResponseExceptionTypes() {
HashMap<Integer, UnexpectedExceptionInformation> exceptionHashMap = new HashMap<>();
for (UnexpectedResponseExceptionType exceptionAnnotation : unexpectedResponseExceptionTypes) {
UnexpectedExceptionInformation exception = new UnexpectedExceptionInformation(exceptionAnnotation.value());
if (exceptionAnnotation.code().length == 0) {
defaultException = exception;
} else {
for (int statusCode : exceptionAnnotation.code()) {
exceptionHashMap.put(statusCode, exception);
}
}
}
if (defaultException == null) {
defaultException = new UnexpectedExceptionInformation(HttpResponseException.class);
}
return exceptionHashMap;
}
} | class SwaggerMethodParser implements HttpResponseDecodeData {
private static final Pattern PATTERN_COLON_SLASH_SLASH = Pattern.compile(":
private final SerializerAdapter serializer;
private final String rawHost;
private final String fullyQualifiedMethodName;
private final HttpMethod httpMethod;
private final String relativePath;
private final List<Substitution> hostSubstitutions = new ArrayList<>();
private final List<Substitution> pathSubstitutions = new ArrayList<>();
private final List<QuerySubstitution> querySubstitutions = new ArrayList<>();
private final List<Substitution> formSubstitutions = new ArrayList<>();
private final List<Substitution> headerSubstitutions = new ArrayList<>();
private final HttpHeaders headers = new HttpHeaders();
private final Integer bodyContentMethodParameterIndex;
private final String bodyContentType;
private final Type bodyJavaType;
private final BitSet expectedStatusCodes;
private final Type returnType;
private final Type returnValueWireType;
private final UnexpectedResponseExceptionType[] unexpectedResponseExceptionTypes;
private Map<Integer, UnexpectedExceptionInformation> exceptionMapping;
private UnexpectedExceptionInformation defaultException;
/**
* Create a SwaggerMethodParser object using the provided fully qualified method name.
*
* @param swaggerMethod the Swagger method to parse.
* @param rawHost the raw host value from the @Host annotation. Before this can be used as the host value in an HTTP
* request, it must be processed through the possible host substitutions.
*/
SwaggerMethodParser(Method swaggerMethod, String rawHost) {
this(swaggerMethod, rawHost, JacksonAdapter.createDefaultSerializerAdapter());
}
SwaggerMethodParser(Method swaggerMethod, String rawHost, SerializerAdapter serializer) {
this.serializer = serializer;
this.rawHost = rawHost;
final Class<?> swaggerInterface = swaggerMethod.getDeclaringClass();
fullyQualifiedMethodName = swaggerInterface.getName() + "." + swaggerMethod.getName();
if (swaggerMethod.isAnnotationPresent(Get.class)) {
this.httpMethod = HttpMethod.GET;
this.relativePath = swaggerMethod.getAnnotation(Get.class).value();
} else if (swaggerMethod.isAnnotationPresent(Put.class)) {
this.httpMethod = HttpMethod.PUT;
this.relativePath = swaggerMethod.getAnnotation(Put.class).value();
} else if (swaggerMethod.isAnnotationPresent(Head.class)) {
this.httpMethod = HttpMethod.HEAD;
this.relativePath = swaggerMethod.getAnnotation(Head.class).value();
} else if (swaggerMethod.isAnnotationPresent(Delete.class)) {
this.httpMethod = HttpMethod.DELETE;
this.relativePath = swaggerMethod.getAnnotation(Delete.class).value();
} else if (swaggerMethod.isAnnotationPresent(Post.class)) {
this.httpMethod = HttpMethod.POST;
this.relativePath = swaggerMethod.getAnnotation(Post.class).value();
} else if (swaggerMethod.isAnnotationPresent(Patch.class)) {
this.httpMethod = HttpMethod.PATCH;
this.relativePath = swaggerMethod.getAnnotation(Patch.class).value();
} else {
throw new MissingRequiredAnnotationException(Arrays.asList(Get.class, Put.class, Head.class,
Delete.class, Post.class, Patch.class), swaggerMethod);
}
returnType = swaggerMethod.getGenericReturnType();
final ReturnValueWireType returnValueWireTypeAnnotation =
swaggerMethod.getAnnotation(ReturnValueWireType.class);
if (returnValueWireTypeAnnotation != null) {
Class<?> returnValueWireType = returnValueWireTypeAnnotation.value();
if (returnValueWireType == Base64Url.class
|| returnValueWireType == UnixTime.class
|| returnValueWireType == DateTimeRfc1123.class) {
this.returnValueWireType = returnValueWireType;
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, List.class)) {
this.returnValueWireType = returnValueWireType.getGenericInterfaces()[0];
} else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, Page.class)) {
this.returnValueWireType = returnValueWireType;
} else {
this.returnValueWireType = null;
}
} else {
this.returnValueWireType = null;
}
if (swaggerMethod.isAnnotationPresent(Headers.class)) {
final Headers headersAnnotation = swaggerMethod.getAnnotation(Headers.class);
final String[] headers = headersAnnotation.value();
for (final String header : headers) {
final int colonIndex = header.indexOf(":");
if (colonIndex >= 0) {
final String headerName = header.substring(0, colonIndex).trim();
if (!headerName.isEmpty()) {
final String headerValue = header.substring(colonIndex + 1).trim();
if (!headerValue.isEmpty()) {
if (headerValue.contains(",")) {
this.headers.set(headerName, Arrays.asList(headerValue.split(",")));
} else {
this.headers.set(headerName, headerValue);
}
}
}
}
}
}
final ExpectedResponses expectedResponses = swaggerMethod.getAnnotation(ExpectedResponses.class);
if (expectedResponses != null && expectedResponses.value().length > 0) {
expectedStatusCodes = new BitSet();
for (int code : expectedResponses.value()) {
expectedStatusCodes.set(code);
}
} else {
expectedStatusCodes = null;
}
unexpectedResponseExceptionTypes = swaggerMethod.getAnnotationsByType(UnexpectedResponseExceptionType.class);
Integer bodyContentMethodParameterIndex = null;
String bodyContentType = null;
Type bodyJavaType = null;
final Annotation[][] allParametersAnnotations = swaggerMethod.getParameterAnnotations();
for (int parameterIndex = 0; parameterIndex < allParametersAnnotations.length; ++parameterIndex) {
final Annotation[] parameterAnnotations = swaggerMethod.getParameterAnnotations()[parameterIndex];
for (final Annotation annotation : parameterAnnotations) {
final Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.equals(HostParam.class)) {
final HostParam hostParamAnnotation = (HostParam) annotation;
hostSubstitutions.add(new Substitution(hostParamAnnotation.value(), parameterIndex,
!hostParamAnnotation.encoded()));
} else if (annotationType.equals(PathParam.class)) {
final PathParam pathParamAnnotation = (PathParam) annotation;
pathSubstitutions.add(new Substitution(pathParamAnnotation.value(), parameterIndex,
!pathParamAnnotation.encoded()));
} else if (annotationType.equals(QueryParam.class)) {
final QueryParam queryParamAnnotation = (QueryParam) annotation;
querySubstitutions.add(new QuerySubstitution(queryParamAnnotation.value(), parameterIndex,
!queryParamAnnotation.encoded(), queryParamAnnotation.multipleQueryParams()));
} else if (annotationType.equals(HeaderParam.class)) {
final HeaderParam headerParamAnnotation = (HeaderParam) annotation;
headerSubstitutions.add(new Substitution(headerParamAnnotation.value(), parameterIndex,
false));
} else if (annotationType.equals(BodyParam.class)) {
final BodyParam bodyParamAnnotation = (BodyParam) annotation;
bodyContentMethodParameterIndex = parameterIndex;
bodyContentType = bodyParamAnnotation.value();
bodyJavaType = swaggerMethod.getGenericParameterTypes()[parameterIndex];
} else if (annotationType.equals(FormParam.class)) {
final FormParam formParamAnnotation = (FormParam) annotation;
formSubstitutions.add(new Substitution(formParamAnnotation.value(), parameterIndex,
!formParamAnnotation.encoded()));
bodyContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
bodyJavaType = String.class;
}
}
}
this.bodyContentMethodParameterIndex = bodyContentMethodParameterIndex;
this.bodyContentType = bodyContentType;
this.bodyJavaType = bodyJavaType;
}
/**
* Get the fully qualified method that was called to invoke this HTTP request.
*
* @return the fully qualified method that was called to invoke this HTTP request
*/
public String getFullyQualifiedMethodName() {
return fullyQualifiedMethodName;
}
/**
* Get the HTTP method that will be used to complete the Swagger method's request.
*
* @return the HTTP method that will be used to complete the Swagger method's request
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Sets the scheme and host to use for HTTP requests for this Swagger method.
*
* @param swaggerMethodArguments The arguments to use for scheme and host substitutions.
* @param urlBuilder The {@link UrlBuilder} that will have its scheme and host set.
*/
public void setSchemeAndHost(Object[] swaggerMethodArguments, UrlBuilder urlBuilder) {
final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments);
final String[] substitutedHostParts = PATTERN_COLON_SLASH_SLASH.split(substitutedHost);
if (substitutedHostParts.length >= 2) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHostParts[1]);
} else if (substitutedHostParts.length == 1) {
urlBuilder.setScheme(substitutedHostParts[0]);
urlBuilder.setHost(substitutedHost);
} else {
urlBuilder.setHost(substitutedHost);
}
}
/**
* Get the path that will be used to complete the Swagger method's request.
*
* @param methodArguments the method arguments to use with the path substitutions
* @return the path value with its placeholders replaced by the matching substitutions
*/
public String setPath(Object[] methodArguments) {
return applySubstitutions(relativePath, pathSubstitutions, methodArguments);
}
/**
* Sets the encoded query parameters that have been added to this value based on the provided method arguments into
* the passed {@link UrlBuilder}.
*
* @param swaggerMethodArguments the arguments that will be used to create the query parameters' values
* @param urlBuilder The {@link UrlBuilder} where the encoded query parameters will be set.
*/
@SuppressWarnings("unchecked")
/**
* Sets the headers that have been added to this value based on the provided method arguments into the passed
* {@link HttpHeaders}.
*
* @param swaggerMethodArguments The arguments that will be used to create the headers' values.
* @param httpHeaders The {@link HttpHeaders} where the header values will be set.
*/
public void setHeaders(Object[] swaggerMethodArguments, HttpHeaders httpHeaders) {
for (HttpHeader header : headers) {
httpHeaders.set(header.getName(), header.getValuesList());
}
if (swaggerMethodArguments == null) {
return;
}
for (Substitution headerSubstitution : headerSubstitutions) {
final int parameterIndex = headerSubstitution.getMethodParameterIndex();
if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) {
final Object methodArgument = swaggerMethodArguments[headerSubstitution.getMethodParameterIndex()];
if (methodArgument instanceof Map) {
@SuppressWarnings("unchecked") final Map<String, ?> headerCollection =
(Map<String, ?>) methodArgument;
final String headerCollectionPrefix = headerSubstitution.getUrlParameterName();
for (final Map.Entry<String, ?> headerCollectionEntry : headerCollection.entrySet()) {
final String headerName = headerCollectionPrefix + headerCollectionEntry.getKey();
final String headerValue = serialize(serializer, headerCollectionEntry.getValue());
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
} else {
final String headerName = headerSubstitution.getUrlParameterName();
final String headerValue = serialize(serializer, methodArgument);
if (headerValue != null) {
httpHeaders.set(headerName, headerValue);
}
}
}
}
}
/**
* Get the {@link Context} passed into the proxy method.
*
* @param swaggerMethodArguments the arguments passed to the proxy method
* @return the context, or {@link Context
*/
public Context setContext(Object[] swaggerMethodArguments) {
Context context = CoreUtils.findFirstOfType(swaggerMethodArguments, Context.class);
return (context != null) ? context : Context.NONE;
}
/**
* Get whether or not the provided response status code is one of the expected status codes for this Swagger
* method.
*
* 1. If the returned int[] is null, then all 2XX status codes are considered as success code.
* 2. If the returned int[] is not-null, only the codes in the array are considered as success code.
*
* @param statusCode the status code that was returned in the HTTP response
* @return whether or not the provided response status code is one of the expected status codes for this Swagger
* method
*/
@Override
public boolean isExpectedResponseStatusCode(final int statusCode) {
return expectedStatusCodes == null
? statusCode < 400
: expectedStatusCodes.get(statusCode);
}
/**
* Get the {@link UnexpectedExceptionInformation} that will be used to generate a RestException if the HTTP response
* status code is not one of the expected status codes.
*
* If an UnexpectedExceptionInformation is not found for the status code the default UnexpectedExceptionInformation
* will be returned.
*
* @param code Exception HTTP status code return from a REST API.
* @return the UnexpectedExceptionInformation to generate an exception to throw or return.
*/
@Override
public UnexpectedExceptionInformation getUnexpectedException(int code) {
if (exceptionMapping == null) {
exceptionMapping = processUnexpectedResponseExceptionTypes();
}
return exceptionMapping.getOrDefault(code, defaultException);
}
/**
* Get the object to be used as the value of the HTTP request.
*
* @param swaggerMethodArguments the method arguments to get the value object from
* @return the object that will be used as the body of the HTTP request
*/
public Object setBody(Object[] swaggerMethodArguments) {
Object result = null;
if (bodyContentMethodParameterIndex != null
&& swaggerMethodArguments != null
&& 0 <= bodyContentMethodParameterIndex
&& bodyContentMethodParameterIndex < swaggerMethodArguments.length) {
result = swaggerMethodArguments[bodyContentMethodParameterIndex];
}
if (!CoreUtils.isNullOrEmpty(formSubstitutions) && swaggerMethodArguments != null) {
result = formSubstitutions.stream()
.map(substitution -> serializeFormData(serializer, substitution.getUrlParameterName(),
swaggerMethodArguments[substitution.getMethodParameterIndex()], substitution.shouldEncode()))
.filter(Objects::nonNull)
.collect(Collectors.joining("&"));
}
return result;
}
/**
* Get the Content-Type of the body of this Swagger method.
*
* @return the Content-Type of the body of this Swagger method
*/
public String getBodyContentType() {
return bodyContentType;
}
/**
* Get the return type for the method that this object describes.
*
* @return the return type for the method that this object describes.
*/
@Override
public Type getReturnType() {
return returnType;
}
/**
* Get the type of the body parameter to this method, if present.
*
* @return the return type of the body parameter to this method
*/
public Type getBodyJavaType() {
return bodyJavaType;
}
/**
* Get the type that the return value will be send across the network as. If returnValueWireType is not null, then
* the raw HTTP response body will need to parsed to this type and then converted to the actual returnType.
*
* @return the type that the raw HTTP response body will be sent as
*/
@Override
public Type getReturnValueWireType() {
return returnValueWireType;
}
private static void addSerializedQueryParameter(SerializerAdapter adapter, Object value, boolean shouldEncode,
UrlBuilder urlBuilder, String parameterName) {
String parameterValue = serialize(adapter, value);
if (parameterValue != null) {
if (shouldEncode) {
parameterValue = UrlEscapers.QUERY_ESCAPER.escape(parameterValue);
}
urlBuilder.addQueryParameter(parameterName, parameterValue);
}
}
private static String serialize(SerializerAdapter serializer, Object value) {
if (value == null) {
return null;
}
if (value instanceof String) {
return (String) value;
} else {
return serializer.serializeRaw(value);
}
}
private static String serializeFormData(SerializerAdapter serializer, String key, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String encodedKey = UrlEscapers.FORM_ESCAPER.escape(key);
if (value instanceof List<?>) {
return ((List<?>) value).stream()
.map(element -> serializeAndEncodeFormValue(serializer, element, shouldEncode))
.filter(Objects::nonNull)
.map(formValue -> encodedKey + "=" + formValue)
.collect(Collectors.joining("&"));
} else {
return encodedKey + "=" + serializeAndEncodeFormValue(serializer, value, shouldEncode);
}
}
private static String serializeAndEncodeFormValue(SerializerAdapter serializer, Object value,
boolean shouldEncode) {
if (value == null) {
return null;
}
String serializedValue = serializer.serializeRaw(value);
return shouldEncode ? UrlEscapers.FORM_ESCAPER.escape(serializedValue) : serializedValue;
}
private String applySubstitutions(String originalValue, Iterable<Substitution> substitutions,
Object[] methodArguments) {
String result = originalValue;
if (methodArguments != null) {
for (Substitution substitution : substitutions) {
final int substitutionParameterIndex = substitution.getMethodParameterIndex();
if (0 <= substitutionParameterIndex && substitutionParameterIndex < methodArguments.length) {
final Object methodArgument = methodArguments[substitutionParameterIndex];
String substitutionValue = serialize(serializer, methodArgument);
if (substitutionValue != null && !substitutionValue.isEmpty() && substitution.shouldEncode()) {
substitutionValue = UrlEscapers.PATH_ESCAPER.escape(substitutionValue);
}
if (substitutionValue == null) {
substitutionValue = "";
}
result = result.replace("{" + substitution.getUrlParameterName() + "}", substitutionValue);
}
}
}
return result;
}
private Map<Integer, UnexpectedExceptionInformation> processUnexpectedResponseExceptionTypes() {
HashMap<Integer, UnexpectedExceptionInformation> exceptionHashMap = new HashMap<>();
for (UnexpectedResponseExceptionType exceptionAnnotation : unexpectedResponseExceptionTypes) {
UnexpectedExceptionInformation exception = new UnexpectedExceptionInformation(exceptionAnnotation.value());
if (exceptionAnnotation.code().length == 0) {
defaultException = exception;
} else {
for (int statusCode : exceptionAnnotation.code()) {
exceptionHashMap.put(statusCode, exception);
}
}
}
if (defaultException == null) {
defaultException = new UnexpectedExceptionInformation(HttpResponseException.class);
}
return exceptionHashMap;
}
} |
All input validation should happen before performing any operations on the input. Here `ServiceBusSharedKeyCredential` should not be created until `fullyQualifiedNamespace` param is validated. | public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ServiceBusConstants.TOKEN_VALIDITY);
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
} | } | public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ServiceBusConstants.TOKEN_VALIDITY);
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureNamedKeyCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureSasCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature());
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType,
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureNamedKeyCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureSasCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature());
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType,
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} |
This overwrites the value set in the previous overload. So, the order of calls to `credential()` decides which credential is being used. Instead, we should do the validate in `build` method and throw exception if both are set. | public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature());
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
} | this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature()); | public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature());
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureNamedKeyCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ServiceBusConstants.TOKEN_VALIDITY);
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureSasCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType,
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureNamedKeyCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ServiceBusConstants.TOKEN_VALIDITY);
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureSasCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType,
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} |
According to your comment, fixed in the new version. | public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ServiceBusConstants.TOKEN_VALIDITY);
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
} | } | public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ServiceBusConstants.TOKEN_VALIDITY);
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureNamedKeyCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureSasCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature());
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType,
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureNamedKeyCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureSasCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature());
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType,
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} |
According to your comment, fixed in the new version. | public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature());
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
} | this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature()); | public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureSasCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getSignature());
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureNamedKeyCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ServiceBusConstants.TOKEN_VALIDITY);
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureSasCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType,
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureNamedKeyCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, AzureNamedKeyCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
Objects.requireNonNull(credential, "'credential' cannot be null.");
this.credentials = new ServiceBusSharedKeyCredential(credential.getAzureNamedKey().getName(),
credential.getAzureNamedKey().getKey(), ServiceBusConstants.TOKEN_VALIDITY);
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link AzureSasCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getAuthorizationScope());
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType,
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler,
options, verificationMode, product, clientVersion);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} |
I don't think this will ever be null because we always `return this;` | public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertNotNull(new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature)));
} | .credential(fullyQualifiedNamespace, eventHubName, | public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
} | class EventHubClientBuilderTest {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertNotNull(new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
}
@Test
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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 EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
}
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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);
}
}
} |
According to your comment in the new revision amendments have been made. | public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertNotNull(new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature)));
} | .credential(fullyQualifiedNamespace, eventHubName, | public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
} | class EventHubClientBuilderTest {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertNotNull(new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
}
@Test
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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 EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
}
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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);
}
}
} |
This will never be sent because it needs to be subscribed to. ```java try { StepVerifier.create(asyncProducerClient.send(testData)) .verifyComplete(); } finally { // Please close client regardless of success or failure because we need to clean up resources. asyncProducerClient.close(); } ``` You don't have to create the asyncConsumerClient and receive below. If the send does not complete in the lines above, the credential is invalid. | public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();;
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
asyncProducerClient.send(testData);
EventHubConsumerAsyncClient asyncConsumerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.buildAsyncConsumerClient();
StepVerifier.create(asyncConsumerClient.receive())
.assertNext(consumer -> Assertions.assertEquals(consumer.getData().getBody(), TEST_CONTENTS.getBytes(UTF_8)))
.verifyComplete();
asyncProducerClient.close();
asyncConsumerClient.close();
} | asyncProducerClient.send(testData); | public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
} | class EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec "
+ "vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. "
+ "Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet "
+ "urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus "
+ "luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \n"
+ "Ut sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, "
+ "condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. "
+ "Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. "
+ "Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh "
+ "euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id "
+ "elit scelerisque, in elementum nulla pharetra. \n"
+ "Aenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a "
+ "lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem"
+ " sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices "
+ "arcu mattis. Aliquam erat volutpat. \n"
+ "Aenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. "
+ "Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris"
+ " consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris "
+ "purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie "
+ "suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \n"
+ "Donec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio "
+ "dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum "
+ "eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum "
+ "gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
asyncProducerClient.send(testData);
EventHubConsumerAsyncClient asyncConsumerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.buildAsyncConsumerClient();
StepVerifier.create(asyncConsumerClient.receive())
.assertNext(consumer -> Assertions.assertEquals(consumer.getData().getBody(), TEST_CONTENTS.getBytes(UTF_8)))
.verifyComplete();
asyncProducerClient.close();
asyncConsumerClient.close();
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
}
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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 EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
}
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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);
}
}
} |
According to your comment in the new revision amendments have been made. | public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();;
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
asyncProducerClient.send(testData);
EventHubConsumerAsyncClient asyncConsumerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.buildAsyncConsumerClient();
StepVerifier.create(asyncConsumerClient.receive())
.assertNext(consumer -> Assertions.assertEquals(consumer.getData().getBody(), TEST_CONTENTS.getBytes(UTF_8)))
.verifyComplete();
asyncProducerClient.close();
asyncConsumerClient.close();
} | asyncProducerClient.send(testData); | public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
} | class EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec "
+ "vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. "
+ "Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet "
+ "urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus "
+ "luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \n"
+ "Ut sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, "
+ "condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. "
+ "Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. "
+ "Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh "
+ "euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id "
+ "elit scelerisque, in elementum nulla pharetra. \n"
+ "Aenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a "
+ "lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem"
+ " sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices "
+ "arcu mattis. Aliquam erat volutpat. \n"
+ "Aenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. "
+ "Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris"
+ " consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris "
+ "purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie "
+ "suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \n"
+ "Donec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio "
+ "dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum "
+ "eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum "
+ "gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
asyncProducerClient.send(testData);
EventHubConsumerAsyncClient asyncConsumerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.buildAsyncConsumerClient();
StepVerifier.create(asyncConsumerClient.receive())
.assertNext(consumer -> Assertions.assertEquals(consumer.getData().getBody(), TEST_CONTENTS.getBytes(UTF_8)))
.verifyComplete();
asyncProducerClient.close();
asyncConsumerClient.close();
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
}
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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 EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
}
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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);
}
}
} |
Is this not a fluent class? Basically will this pattern not work here.. SmsRecipient recipient = new SmsRecipient() .recipient.setTo(s) .recipient.setRepeatabilityRequestId(UUID.randomUUID().toString()) .recipient.setRepeatabilityFirstSent(OffsetDateTime.now(ZoneOffset.UTC) | private SendMessageRequest createSendMessageRequest(String from, Iterable<String> smsRecipient, String message, SmsSendOptions options) {
SendMessageRequest request = new SendMessageRequest();
List<SmsRecipient> recipients = new ArrayList<SmsRecipient>();
for (String s : smsRecipient) {
SmsRecipient recipient = new SmsRecipient();
recipient.setTo(s);
recipient.setRepeatabilityRequestId(UUID.randomUUID().toString());
recipient.setRepeatabilityFirstSent(OffsetDateTime.now(ZoneOffset.UTC)
.format(DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US)));
recipients.add(recipient);
}
request.setFrom(from)
.setSmsRecipients(recipients)
.setMessage(message)
.setSmsSendOptions(options);
return request;
} | SmsRecipient recipient = new SmsRecipient(); | private SendMessageRequest createSendMessageRequest(String from, Iterable<String> smsRecipient, String message, SmsSendOptions options) {
SendMessageRequest request = new SendMessageRequest();
List<SmsRecipient> recipients = new ArrayList<SmsRecipient>();
for (String s : smsRecipient) {
SmsRecipient recipient = new SmsRecipient()
.setTo(s)
.setRepeatabilityRequestId(UUID.randomUUID().toString())
.setRepeatabilityFirstSent(OffsetDateTime.now(ZoneOffset.UTC)
.format(DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US)));
recipients.add(recipient);
}
request.setFrom(from)
.setSmsRecipients(recipients)
.setMessage(message)
.setSmsSendOptions(options);
return request;
} | class SmsAsyncClient {
private final SmsImpl smsClient;
private final ClientLogger logger = new ClientLogger(SmsAsyncClient.class);
SmsAsyncClient(AzureCommunicationSMSServiceImpl smsServiceClient) {
smsClient = smsServiceClient.getSms();
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message) {
return send(from, to, message, null, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @param options set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return The Sms send result.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message, SmsSendOptions options) {
return send(from, to, message, options, null);
}
Mono<SmsSendResult> send(String from, String to, String message, SmsSendOptions options, Context context) {
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
List<String> recipients = Arrays.asList(to);
SendMessageRequest request = createSendMessageRequest(from, recipients, message, options);
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return smsClient.sendAsync(request, contextValue)
.flatMap((SmsSendResponse response) -> {
List<SmsSendResult> smsSendResults = convertSmsSendResults(response.getValue());
return Mono.just(smsSendResults.get(0));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message) {
return sendWithResponse(from, to, message, null)
.map(response -> response.getValue());
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @param options set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Iterable<SmsSendResult>>> sendWithResponse(String from, Iterable<String> to, String message, SmsSendOptions options) {
return sendWithResponse(from, to, message, options, null);
}
Mono<Response<Iterable<SmsSendResult>>> sendWithResponse(String from, Iterable<String> to, String message, SmsSendOptions options, Context context) {
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
SendMessageRequest request = createSendMessageRequest(from, to, message, options);
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.smsClient.sendWithResponseAsync(request, contextValue)
.flatMap((Response<SmsSendResponse> response) -> {
Iterable<SmsSendResult> smsSendResults = convertSmsSendResults(response.getValue().getValue());
return Mono.just(new SimpleResponse<Iterable<SmsSendResult>>(response, smsSendResults));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private List<SmsSendResult> convertSmsSendResults(Iterable<SmsSendResponseItem> resultsIterable) {
List<SmsSendResult> iterableWrapper = new ArrayList<>();
for (SmsSendResponseItem item : resultsIterable) {
iterableWrapper.add(new SmsSendResult(
item.getTo(),
item.getMessageId(),
item.getHttpStatusCode(),
item.isSuccessful(),
item.getErrorMessage()));
}
return iterableWrapper;
}
} | class SmsAsyncClient {
private final SmsImpl smsClient;
private final ClientLogger logger = new ClientLogger(SmsAsyncClient.class);
SmsAsyncClient(AzureCommunicationSMSServiceImpl smsServiceClient) {
smsClient = smsServiceClient.getSms();
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message) {
return send(from, to, message, null, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @param options set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return The Sms send result.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message, SmsSendOptions options) {
return send(from, to, message, options, null);
}
Mono<SmsSendResult> send(String from, String to, String message, SmsSendOptions options, Context context) {
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
List<String> recipients = Arrays.asList(to);
SendMessageRequest request = createSendMessageRequest(from, recipients, message, options);
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return smsClient.sendAsync(request, contextValue)
.flatMap((SmsSendResponse response) -> {
List<SmsSendResult> smsSendResults = convertSmsSendResults(response.getValue());
return Mono.just(smsSendResults.get(0));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message) {
return sendWithResponse(from, to, message, null)
.map(response -> response.getValue());
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @param options set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Iterable<SmsSendResult>>> sendWithResponse(String from, Iterable<String> to, String message, SmsSendOptions options) {
return sendWithResponse(from, to, message, options, null);
}
Mono<Response<Iterable<SmsSendResult>>> sendWithResponse(String from, Iterable<String> to, String message, SmsSendOptions options, Context context) {
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
SendMessageRequest request = createSendMessageRequest(from, to, message, options);
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.smsClient.sendWithResponseAsync(request, contextValue)
.flatMap((Response<SmsSendResponse> response) -> {
Iterable<SmsSendResult> smsSendResults = convertSmsSendResults(response.getValue().getValue());
return Mono.just(new SimpleResponse<Iterable<SmsSendResult>>(response, smsSendResults));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private List<SmsSendResult> convertSmsSendResults(Iterable<SmsSendResponseItem> resultsIterable) {
List<SmsSendResult> iterableWrapper = new ArrayList<>();
for (SmsSendResponseItem item : resultsIterable) {
iterableWrapper.add(new SmsSendResult(
item.getTo(),
item.getMessageId(),
item.getHttpStatusCode(),
item.isSuccessful(),
item.getErrorMessage()));
}
return iterableWrapper;
}
} |
The subscribe is not blocking. the callback actually runs on background thread. So this test would end prematurely. ```java try { StepVerifier.create(asyncProducerClient.createBatch() .flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) .verifyComplete(); } finally { asyncProducerClient.close(); } ``` | public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
try {
asyncProducerClient.createBatch().subscribe(batch -> {
batch.getEvents().add(testData);
StepVerifier.create(asyncProducerClient.send(batch))
.verifyComplete();
});
} finally {
asyncProducerClient.close();
}
} | asyncProducerClient.createBatch().subscribe(batch -> { | public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
} | class EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
try {
asyncProducerClient.createBatch().subscribe(batch -> {
batch.getEvents().add(testData);
StepVerifier.create(asyncProducerClient.send(batch))
.verifyComplete();
});
} finally {
asyncProducerClient.close();
}
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
}
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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 EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
}
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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);
}
}
} |
According to your comment in the new revision amendments have been made. | public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
try {
asyncProducerClient.createBatch().subscribe(batch -> {
batch.getEvents().add(testData);
StepVerifier.create(asyncProducerClient.send(batch))
.verifyComplete();
});
} finally {
asyncProducerClient.close();
}
} | asyncProducerClient.createBatch().subscribe(batch -> { | public void sendAndReceiveEventByAzureNameKeyCredential() {
ConnectionStringProperties properties = getConnectionStringProperties();
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessKeyName = properties.getSharedAccessKeyName();
String sharedAccessKey = properties.getSharedAccessKey();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
} | class EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
try {
asyncProducerClient.createBatch().subscribe(batch -> {
batch.getEvents().add(testData);
StepVerifier.create(asyncProducerClient.send(batch))
.verifyComplete();
});
} finally {
asyncProducerClient.close();
}
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
}
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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 EventHubClientBuilderTest extends IntegrationTestBase {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
private static final String PROXY_HOST = "127.0.0.1";
private static final String PROXY_PORT = "3128";
private static final String CORRECT_CONNECTION_STRING = String.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static final Proxy PROXY_ADDRESS = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, Integer.parseInt(PROXY_PORT)));
private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit.";
EventHubClientBuilderTest() {
super(new ClientLogger(EventHubClientBuilderTest.class));
}
@Test
public void missingConnectionString() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
public void defaultProxyConfigurationBuilder() {
final EventHubClientBuilder builder = new EventHubClientBuilder();
final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient();
assertNotNull(client);
}
@Test
public void customNoneProxyConfigurationBuilder() {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.NONE, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS);
assertNotNull(builder.buildAsyncClient());
}
@Test
public void throwsWithProxyWhenTransportTypeNotChanged() {
assertThrows(IllegalArgumentException.class, () -> {
final ProxyOptions proxyConfig = new ProxyOptions(ProxyAuthenticationType.BASIC, PROXY_ADDRESS,
null, null);
final EventHubClientBuilder builder = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.proxyOptions(proxyConfig);
assertNotNull(builder.buildAsyncClient());
});
}
@Test
public void testConnectionStringWithSas() {
String connectionStringWithNoEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value";
String connectionStringWithEntityPath = "Endpoint=sb:
+ "SharedAccessSignature=SharedAccessSignature test-value;EntityPath=eh-name";
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath, "eh-name"));
assertNotNull(new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithNoEntityPath));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.connectionString(connectionStringWithEntityPath, "eh-name-mismatch"));
}
@MethodSource("getProxyConfigurations")
@ParameterizedTest
public void testProxyOptionsConfiguration(String proxyConfiguration, boolean expectedClientCreation) {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
configuration = configuration.put(Configuration.PROPERTY_HTTP_PROXY, proxyConfiguration);
boolean clientCreated = false;
try {
EventHubConsumerAsyncClient asyncClient = new EventHubClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.configuration(configuration)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.transportType(AmqpTransportType.AMQP_WEB_SOCKETS)
.buildAsyncConsumerClient();
clientCreated = true;
} catch (Exception ex) {
}
Assertions.assertEquals(expectedClientCreation, clientCreated);
}
@Test
@Test
public void sendAndReceiveEventByAzureSasCredential() {
ConnectionStringProperties properties = getConnectionStringProperties(true);
String fullyQualifiedNamespace = getFullyQualifiedDomainName();
String sharedAccessSignature = properties.getSharedAccessSignature();
String eventHubName = getEventHubName();
final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8));
EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName,
new AzureSasCredential(sharedAccessSignature))
.buildAsyncProducerClient();
try {
StepVerifier.create(
asyncProducerClient.createBatch().flatMap(batch -> {
assertTrue(batch.tryAdd(testData));
return asyncProducerClient.send(batch);
})
).verifyComplete();
} finally {
asyncProducerClient.close();
}
}
@Test
public void testConnectionWithAzureNameKeyCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessKeyName = "SharedAccessKeyName test-value";
String sharedAccessKey = "SharedAccessKey test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName,
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "",
new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureNamedKeyCredential) null));
}
@Test
public void testConnectionWithAzureSasCredential() {
String fullyQualifiedNamespace = "sb-name.servicebus.windows.net";
String sharedAccessSignature = "SharedAccessSignature test-value";
String eventHubName = "test-event-hub-name";
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(null, eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, null, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential("", eventHubName, new AzureSasCredential(sharedAccessSignature)));
assertThrows(IllegalArgumentException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, "", new AzureSasCredential(sharedAccessSignature)));
assertThrows(NullPointerException.class, () -> new EventHubClientBuilder()
.credential(fullyQualifiedNamespace, eventHubName, (AzureSasCredential) null));
}
private static Stream<Arguments> getProxyConfigurations() {
return Stream.of(
Arguments.of("http:
Arguments.of("localhost:8080", true),
Arguments.of("localhost_8080", false),
Arguments.of("http:
Arguments.of("http:
Arguments.of(":8080", false),
Arguments.of("http:
Arguments.of("sub.example.com:8080", true),
Arguments.of("https:
Arguments.of("https:
);
}
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);
}
}
} |
Strong said , we should not use "ex.printStackTrace()" > we should never have "System.out.println" or "e.printStackTrace()" in our code, use logger instead | public KeyVaultTrustManager(KeyStore keyStore) {
this.keyStore = keyStore;
if (this.keyStore == null) {
try {
this.keyStore = KeyStore.getInstance(KeyVaultKeyStore.KEY_STORE_TYPE);
this.keyStore.load(null, null);
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException ex) {
ex.printStackTrace();
}
}
try {
TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
factory.init(keyStore);
defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0];
} catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) {
ex.printStackTrace();
}
if (defaultTrustManager == null) {
try {
TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "IbmJSSE");
factory.init(keyStore);
defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0];
} catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) {
ex.printStackTrace();
}
}
} | ex.printStackTrace(); | public KeyVaultTrustManager(KeyStore keyStore) {
this.keyStore = keyStore;
if (this.keyStore == null) {
try {
this.keyStore = KeyStore.getInstance(KeyVaultKeyStore.KEY_STORE_TYPE);
this.keyStore.load(null, null);
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException ex) {
LOGGER.log(WARNING, "Unable to get AzureKeyVault keystore.", ex);
}
}
try {
TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
factory.init(keyStore);
defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0];
} catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) {
LOGGER.log(WARNING, "Unable to get the trust manager factory.", ex);
}
if (defaultTrustManager == null) {
try {
TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "IbmJSSE");
factory.init(keyStore);
defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0];
} catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) {
LOGGER.log(WARNING, "Unable to get the trust manager factory.", ex);
}
}
} | class KeyVaultTrustManager extends X509ExtendedTrustManager {
/**
* Stores the default trust manager.
*/
private X509TrustManager defaultTrustManager;
/**
* Stores the keystore.
*/
private KeyStore keyStore;
/**
* Constructor.
*
* @param keyStore the keystore.
*/
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
boolean pass = true;
/*
* Step 1 - see if the default trust manager passes.
*/
try {
defaultTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException ce) {
pass = false;
}
/*
* Step 2 - see if the certificate exists in the keystore.
*/
if (!pass) {
String alias = null;
try {
alias = keyStore.getCertificateAlias(chain[0]);
} catch (KeyStoreException kse) {
kse.printStackTrace();
}
if (alias == null) {
throw new CertificateException("Unable to verify in keystore");
}
}
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
boolean pass = true;
/*
* Step 1 - see if the default trust manager passes.
*/
try {
defaultTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException ce) {
pass = false;
}
/*
* Step 2 - see if the certificate exists in the keystore.
*/
if (!pass) {
String alias = null;
try {
alias = keyStore.getCertificateAlias(chain[0]);
} catch (KeyStoreException kse) {
kse.printStackTrace();
}
if (alias == null) {
throw new CertificateException("Unable to verify in keystore");
}
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
checkClientTrusted(chain, authType);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
checkServerTrusted(chain, authType);
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
checkClientTrusted(chain, authType);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
checkServerTrusted(chain, authType);
}
} | class KeyVaultTrustManager extends X509ExtendedTrustManager {
/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultTrustManager.class.getName());
/**
* Stores the default trust manager.
*/
private X509TrustManager defaultTrustManager;
/**
* Stores the keystore.
*/
private KeyStore keyStore;
/**
* Constructor.
*
* @param keyStore the keystore.
*/
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
boolean pass = true;
/*
* Step 1 - see if the default trust manager passes.
*/
try {
defaultTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException ce) {
pass = false;
}
/*
* Step 2 - see if the certificate exists in the keystore.
*/
if (!pass) {
String alias = null;
try {
alias = keyStore.getCertificateAlias(chain[0]);
} catch (KeyStoreException kse) {
LOGGER.log(WARNING, "Unable to get the certificate in AzureKeyVault keystore.", kse);
}
if (alias == null) {
throw new CertificateException("Unable to verify in keystore");
}
}
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
boolean pass = true;
/*
* Step 1 - see if the default trust manager passes.
*/
try {
defaultTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException ce) {
pass = false;
}
/*
* Step 2 - see if the certificate exists in the keystore.
*/
if (!pass) {
String alias = null;
try {
alias = keyStore.getCertificateAlias(chain[0]);
} catch (KeyStoreException kse) {
LOGGER.log(WARNING, "Unable to get the certificate in AzureKeyVault keystore.", kse);
}
if (alias == null) {
throw new CertificateException("Unable to verify in keystore");
}
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
checkClientTrusted(chain, authType);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
checkServerTrusted(chain, authType);
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
checkClientTrusted(chain, authType);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
checkServerTrusted(chain, authType);
}
} |
Can you fix the formatting issues here? and make 218 and 219 the same line? | public void repeatability(HttpClient httpClient) {
PipedOutputStream osPipe = new PipedOutputStream();
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessagesSync");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE)
)
.assertNext(requestResponse -> {
requestResponse.getRequest().getBody().map(bodyBuffer -> {
String bodyRequest = new String(bodyBuffer.array());
assertTrue(bodyRequest.contains("repeatabilityRequestId"));
return null;
});
}
)
.verifyComplete();
} | ) | public void repeatability(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "repeatability");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE))
.assertNext(requestResponse -> {
String bodyRequest = new String(requestResponse.getRequest().getBody().blockLast().array());
assertTrue(bodyRequest.contains("repeatabilityRequestId"));
assertTrue(bodyRequest.contains("repeatabilityFirstSent"));
})
.verifyComplete();
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnableSmsTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsUsingConnectionString");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroup");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE))
.assertNext((Iterable<SmsSendResult> sendResults) -> {
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options))
.assertNext((Response<Iterable<SmsSendResult>> response) -> {
for (SmsSendResult result : response.getValue()) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumberWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options))
.assertNext((SmsSendResult sendResult) -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 401).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnableSmsTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsUsingConnectionString");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroup");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE))
.assertNext((Iterable<SmsSendResult> sendResults) -> {
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options))
.assertNext((Response<Iterable<SmsSendResult>> response) -> {
for (SmsSendResult result : response.getValue()) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumberWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options))
.assertNext((SmsSendResult sendResult) -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 401).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} |
We should probably add a check for the RepeatabilityFirstSent as well | public void repeatability(HttpClient httpClient) {
PipedOutputStream osPipe = new PipedOutputStream();
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessagesSync");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE)
)
.assertNext(requestResponse -> {
requestResponse.getRequest().getBody().map(bodyBuffer -> {
String bodyRequest = new String(bodyBuffer.array());
assertTrue(bodyRequest.contains("repeatabilityRequestId"));
return null;
});
}
)
.verifyComplete();
} | assertTrue(bodyRequest.contains("repeatabilityRequestId")); | public void repeatability(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "repeatability");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE))
.assertNext(requestResponse -> {
String bodyRequest = new String(requestResponse.getRequest().getBody().blockLast().array());
assertTrue(bodyRequest.contains("repeatabilityRequestId"));
assertTrue(bodyRequest.contains("repeatabilityFirstSent"));
})
.verifyComplete();
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnableSmsTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsUsingConnectionString");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroup");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE))
.assertNext((Iterable<SmsSendResult> sendResults) -> {
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options))
.assertNext((Response<Iterable<SmsSendResult>> response) -> {
for (SmsSendResult result : response.getValue()) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumberWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options))
.assertNext((SmsSendResult sendResult) -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 401).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnableSmsTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsUsingConnectionString");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroup");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE))
.assertNext((Iterable<SmsSendResult> sendResults) -> {
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options))
.assertNext((Response<Iterable<SmsSendResult>> response) -> {
for (SmsSendResult result : response.getValue()) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumberWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options))
.assertNext((SmsSendResult sendResult) -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 401).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} |
I checked this issue again. Service already resolved the issue. I will close this issue. Thanks Mariana | private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) {
return new JobManifestTasks()
.setEntityRecognitionTasks(actions.getRecognizeEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntitiesTask entitiesTask = new EntitiesTask();
entitiesTask.setParameters(
new EntitiesTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType())));
return entitiesTask;
}).collect(Collectors.toList()))
.setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizePiiEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final PiiTask piiTask = new PiiTask();
piiTask.setParameters(
new PiiTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
.setDomain(PiiTaskParametersDomain.fromString(
action.getDomainFilter() == null ? null
: action.getDomainFilter().toString()))
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType()))
.setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))
);
return piiTask;
}).collect(Collectors.toList()))
.setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesOptions() == null ? null
: StreamSupport.stream(actions.getExtractKeyPhrasesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask();
keyPhrasesTask.setParameters(
new KeyPhrasesTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
);
return keyPhrasesTask;
}).collect(Collectors.toList()))
.setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeLinkedEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntityLinkingTask entityLinkingTask = new EntityLinkingTask();
entityLinkingTask.setParameters(
new EntityLinkingTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
);
return entityLinkingTask;
}).collect(Collectors.toList()))
.setSentimentAnalysisTasks(actions.getAnalyzeSentimentOptions() == null ? null
: StreamSupport.stream(actions.getAnalyzeSentimentOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask();
sentimentAnalysisTask.setParameters(
new SentimentAnalysisTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
);
return sentimentAnalysisTask;
}).collect(Collectors.toList()));
} | new SentimentAnalysisTaskParameters() | private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) {
return new JobManifestTasks()
.setEntityRecognitionTasks(actions.getRecognizeEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntitiesTask entitiesTask = new EntitiesTask();
entitiesTask.setParameters(
new EntitiesTaskParameters()
.setModelVersion(action.getModelVersion())
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType())));
return entitiesTask;
}).collect(Collectors.toList()))
.setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizePiiEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final PiiTask piiTask = new PiiTask();
piiTask.setParameters(
new PiiTaskParameters()
.setModelVersion(action.getModelVersion())
.setDomain(PiiTaskParametersDomain.fromString(
action.getDomainFilter() == null ? null
: action.getDomainFilter().toString()))
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType()))
.setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))
);
return piiTask;
}).collect(Collectors.toList()))
.setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesOptions() == null ? null
: StreamSupport.stream(actions.getExtractKeyPhrasesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask();
keyPhrasesTask.setParameters(
new KeyPhrasesTaskParameters()
.setModelVersion(action.getModelVersion())
);
return keyPhrasesTask;
}).collect(Collectors.toList()))
.setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeLinkedEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntityLinkingTask entityLinkingTask = new EntityLinkingTask();
entityLinkingTask.setParameters(
new EntityLinkingTaskParameters()
.setModelVersion(action.getModelVersion())
);
return entityLinkingTask;
}).collect(Collectors.toList()))
.setSentimentAnalysisTasks(actions.getAnalyzeSentimentOptions() == null ? null
: StreamSupport.stream(actions.getAnalyzeSentimentOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask();
sentimentAnalysisTask.setParameters(
new SentimentAnalysisTaskParameters()
.setModelVersion(action.getModelVersion())
);
return sentimentAnalysisTask;
}).collect(Collectors.toList()));
} | class AnalyzeActionsAsyncClient {
private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks";
private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks";
private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks";
private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks";
private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks";
private static final String REGEX_ACTION_ERROR_TARGET = "
+ "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)";
private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class);
private final TextAnalyticsClientImpl service;
AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
PollerFlux<AnalyzeActionsOperationDetail, PagedFlux<AnalyzeActionsResult>> beginAnalyzeActions(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail textAnalyticsOperationResult =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper
.setOperationId(textAnalyticsOperationResult,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return textAnalyticsOperationResult;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext)))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
PollerFlux<AnalyzeActionsOperationDetail, PagedIterable<AnalyzeActionsResult>> beginAnalyzeActionsIterable(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail operationDetail =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return operationDetail;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperationIterable(operationId -> Mono.just(new PagedIterable<>(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext))))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>>
activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) {
return pollingContext -> {
try {
return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>>
pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) {
return pollingContext -> {
try {
final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse =
pollingContext.getLatestResponse();
final String operationId = operationResultPollResponse.getValue().getOperationId();
return pollingFunction.apply(operationId)
.flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse))
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PagedFlux<AnalyzeActionsResult>>>
fetchingOperation(Function<String, Mono<PagedFlux<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PagedIterable<AnalyzeActionsResult>>>
fetchingOperationIterable(Function<String, Mono<PagedIterable<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
PagedFlux<AnalyzeActionsResult> getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip,
boolean showStats, Context context) {
return new PagedFlux<>(
() -> getPage(null, operationId, top, skip, showStats, context),
continuationToken -> getPage(continuationToken, operationId, top, skip, showStats, context));
}
Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top,
Integer skip, boolean showStats, Context context) {
if (continuationToken != null) {
final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken);
final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null);
final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null);
final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false);
return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} else {
return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
}
}
private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) {
final AnalyzeJobState analyzeJobState = response.getValue();
return new PagedResponseBase<Void, AnalyzeActionsResult>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
Arrays.asList(toAnalyzeActionsResult(analyzeJobState)),
analyzeJobState.getNextLink(),
null);
}
private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) {
TasksStateTasks tasksStateTasks = analyzeJobState.getTasks();
final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems =
tasksStateTasks.getEntityRecognitionPiiTasks();
final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems =
tasksStateTasks.getEntityRecognitionTasks();
final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks =
tasksStateTasks.getKeyPhraseExtractionTasks();
final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems =
tasksStateTasks.getEntityLinkingTasks();
final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems =
tasksStateTasks.getSentimentAnalysisTasks();
List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>();
List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>();
List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>();
List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>();
List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>();
if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) {
for (int i = 0; i < entityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i);
final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult();
final EntitiesResult results = taskItem.getResults();
if (results != null) {
RecognizeEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizeEntitiesResultCollectionResponse(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(piiTasksItems)) {
for (int i = 0; i < piiTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i);
final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult();
final PiiResult results = taskItem.getResults();
if (results != null) {
RecognizePiiEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizePiiEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizePiiEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) {
for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) {
final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i);
final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult();
final KeyPhraseResult results = taskItem.getResults();
if (results != null) {
ExtractKeyPhrasesActionResultPropertiesHelper.setResult(actionResult,
toExtractKeyPhrasesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
extractKeyPhrasesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) {
for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i);
final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult();
final EntityLinkingResult results = taskItem.getResults();
if (results != null) {
RecognizeLinkedEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizeLinkedEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeLinkedEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) {
for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) {
final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i);
final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult();
final SentimentResponse results = taskItem.getResults();
if (results != null) {
AnalyzeSentimentActionResultPropertiesHelper.setResult(actionResult,
toAnalyzeSentimentResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
analyzeSentimentActionResults.add(actionResult);
}
}
final List<TextAnalyticsError> errors = analyzeJobState.getErrors();
if (!CoreUtils.isNullOrEmpty(errors)) {
for (TextAnalyticsError error : errors) {
final String[] targetPair = parseActionErrorTarget(error.getTarget());
final String taskName = targetPair[0];
final Integer taskIndex = Integer.valueOf(targetPair[1]);
final TextAnalyticsActionResult actionResult;
if (ENTITY_RECOGNITION_TASKS.equals(taskName)) {
actionResult = recognizeEntitiesActionResults.get(taskIndex);
} else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) {
actionResult = recognizePiiEntitiesActionResults.get(taskIndex);
} else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) {
actionResult = extractKeyPhrasesActionResults.get(taskIndex);
} else if (ENTITY_LINKING_TASKS.equals(taskName)) {
actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex);
} else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) {
actionResult = analyzeSentimentActionResults.get(taskIndex);
} else {
throw logger.logExceptionAsError(new RuntimeException(
"Invalid task name in target reference, " + taskName));
}
TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true);
TextAnalyticsActionResultPropertiesHelper.setError(actionResult,
new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(
error.getCode() == null ? null : error.getCode().toString()),
error.getMessage(), null));
}
}
final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult();
final RequestStatistics requestStatistics = analyzeJobState.getStatistics();
TextDocumentBatchStatistics batchStatistics = null;
if (requestStatistics != null) {
batchStatistics = new TextDocumentBatchStatistics(
requestStatistics.getDocumentsCount(), requestStatistics.getErroneousDocumentsCount(),
requestStatistics.getValidDocumentsCount(), requestStatistics.getTransactionsCount()
);
}
AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, batchStatistics);
AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizePiiEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult,
IterableStream.of(extractKeyPhrasesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeLinkedEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult,
IterableStream.of(analyzeSentimentActionResults));
return analyzeActionsResult;
}
private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse(
Response<AnalyzeJobState> analyzeJobStateResponse,
PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) {
LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) {
switch (analyzeJobStateResponse.getValue().getStatus()) {
case NOT_STARTED:
case RUNNING:
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case SUCCEEDED:
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case CANCELLED:
status = LongRunningOperationStatus.USER_CANCELLED;
break;
default:
status = LongRunningOperationStatus.fromString(
analyzeJobStateResponse.getValue().getStatus().toString(), true);
break;
}
}
AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getDisplayName());
AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getCreatedDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getExpirationDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getLastUpdateDateTime());
final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks();
AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(),
tasksResult.getFailed());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(),
tasksResult.getInProgress());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded(
operationResultPollResponse.getValue(), tasksResult.getCompleted());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(),
tasksResult.getTotal());
return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue()));
}
private Context getNotNullContext(Context context) {
return context == null ? Context.NONE : context;
}
private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) {
return options == null ? new AnalyzeActionsOptions() : options;
}
private String getNotNullModelVersion(String modelVersion) {
return modelVersion == null ? "latest" : modelVersion;
}
private String[] parseActionErrorTarget(String targetReference) {
if (CoreUtils.isNullOrEmpty(targetReference)) {
throw logger.logExceptionAsError(new RuntimeException(
"Expected an error with a target field referencing an action but did not get one"));
}
final Pattern pattern = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(targetReference);
String[] taskNameIdPair = new String[2];
while (matcher.find()) {
taskNameIdPair[0] = matcher.group(1);
taskNameIdPair[1] = matcher.group(2);
}
return taskNameIdPair;
}
} | class AnalyzeActionsAsyncClient {
private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks";
private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks";
private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks";
private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks";
private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks";
private static final String REGEX_ACTION_ERROR_TARGET = "
+ "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)";
private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class);
private final TextAnalyticsClientImpl service;
private static final Pattern PATTERN;
static {
PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE);
}
AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
PollerFlux<AnalyzeActionsOperationDetail, PagedFlux<AnalyzeActionsResult>> beginAnalyzeActions(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail textAnalyticsOperationResult =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper
.setOperationId(textAnalyticsOperationResult,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return textAnalyticsOperationResult;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext)))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
PollerFlux<AnalyzeActionsOperationDetail, PagedIterable<AnalyzeActionsResult>> beginAnalyzeActionsIterable(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail operationDetail =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return operationDetail;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperationIterable(operationId -> Mono.just(new PagedIterable<>(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext))))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>>
activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) {
return pollingContext -> {
try {
return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>>
pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) {
return pollingContext -> {
try {
final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse =
pollingContext.getLatestResponse();
final String operationId = operationResultPollResponse.getValue().getOperationId();
return pollingFunction.apply(operationId)
.flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse))
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PagedFlux<AnalyzeActionsResult>>>
fetchingOperation(Function<String, Mono<PagedFlux<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PagedIterable<AnalyzeActionsResult>>>
fetchingOperationIterable(Function<String, Mono<PagedIterable<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
PagedFlux<AnalyzeActionsResult> getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip,
boolean showStats, Context context) {
return new PagedFlux<>(
() -> getPage(null, operationId, top, skip, showStats, context),
continuationToken -> getPage(continuationToken, operationId, top, skip, showStats, context));
}
Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top,
Integer skip, boolean showStats, Context context) {
if (continuationToken != null) {
final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken);
final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null);
final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null);
final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false);
return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} else {
return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
}
}
private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) {
final AnalyzeJobState analyzeJobState = response.getValue();
return new PagedResponseBase<Void, AnalyzeActionsResult>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
Arrays.asList(toAnalyzeActionsResult(analyzeJobState)),
analyzeJobState.getNextLink(),
null);
}
private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) {
TasksStateTasks tasksStateTasks = analyzeJobState.getTasks();
final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems =
tasksStateTasks.getEntityRecognitionPiiTasks();
final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems =
tasksStateTasks.getEntityRecognitionTasks();
final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks =
tasksStateTasks.getKeyPhraseExtractionTasks();
final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems =
tasksStateTasks.getEntityLinkingTasks();
final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems =
tasksStateTasks.getSentimentAnalysisTasks();
List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>();
List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>();
List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>();
List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>();
List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>();
if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) {
for (int i = 0; i < entityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i);
final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult();
final EntitiesResult results = taskItem.getResults();
if (results != null) {
RecognizeEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizeEntitiesResultCollectionResponse(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(piiTasksItems)) {
for (int i = 0; i < piiTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i);
final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult();
final PiiResult results = taskItem.getResults();
if (results != null) {
RecognizePiiEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizePiiEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizePiiEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) {
for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) {
final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i);
final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult();
final KeyPhraseResult results = taskItem.getResults();
if (results != null) {
ExtractKeyPhrasesActionResultPropertiesHelper.setResult(actionResult,
toExtractKeyPhrasesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
extractKeyPhrasesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) {
for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i);
final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult();
final EntityLinkingResult results = taskItem.getResults();
if (results != null) {
RecognizeLinkedEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizeLinkedEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeLinkedEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) {
for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) {
final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i);
final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult();
final SentimentResponse results = taskItem.getResults();
if (results != null) {
AnalyzeSentimentActionResultPropertiesHelper.setResult(actionResult,
toAnalyzeSentimentResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
analyzeSentimentActionResults.add(actionResult);
}
}
final List<TextAnalyticsError> errors = analyzeJobState.getErrors();
if (!CoreUtils.isNullOrEmpty(errors)) {
for (TextAnalyticsError error : errors) {
final String[] targetPair = parseActionErrorTarget(error.getTarget());
final String taskName = targetPair[0];
final Integer taskIndex = Integer.valueOf(targetPair[1]);
final TextAnalyticsActionResult actionResult;
if (ENTITY_RECOGNITION_TASKS.equals(taskName)) {
actionResult = recognizeEntitiesActionResults.get(taskIndex);
} else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) {
actionResult = recognizePiiEntitiesActionResults.get(taskIndex);
} else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) {
actionResult = extractKeyPhrasesActionResults.get(taskIndex);
} else if (ENTITY_LINKING_TASKS.equals(taskName)) {
actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex);
} else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) {
actionResult = analyzeSentimentActionResults.get(taskIndex);
} else {
throw logger.logExceptionAsError(new RuntimeException(
"Invalid task name in target reference, " + taskName));
}
TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true);
TextAnalyticsActionResultPropertiesHelper.setError(actionResult,
new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(
error.getCode() == null ? null : error.getCode().toString()),
error.getMessage(), null));
}
}
final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult();
final RequestStatistics requestStatistics = analyzeJobState.getStatistics();
TextDocumentBatchStatistics batchStatistics = null;
if (requestStatistics != null) {
batchStatistics = new TextDocumentBatchStatistics(
requestStatistics.getDocumentsCount(), requestStatistics.getErroneousDocumentsCount(),
requestStatistics.getValidDocumentsCount(), requestStatistics.getTransactionsCount()
);
}
AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, batchStatistics);
AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizePiiEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult,
IterableStream.of(extractKeyPhrasesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeLinkedEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult,
IterableStream.of(analyzeSentimentActionResults));
return analyzeActionsResult;
}
private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse(
Response<AnalyzeJobState> analyzeJobStateResponse,
PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) {
LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) {
switch (analyzeJobStateResponse.getValue().getStatus()) {
case NOT_STARTED:
case RUNNING:
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case SUCCEEDED:
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case CANCELLED:
status = LongRunningOperationStatus.USER_CANCELLED;
break;
default:
status = LongRunningOperationStatus.fromString(
analyzeJobStateResponse.getValue().getStatus().toString(), true);
break;
}
}
AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getDisplayName());
AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getCreatedDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getExpirationDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getLastUpdateDateTime());
final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks();
AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(),
tasksResult.getFailed());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(),
tasksResult.getInProgress());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded(
operationResultPollResponse.getValue(), tasksResult.getCompleted());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(),
tasksResult.getTotal());
return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue()));
}
private Context getNotNullContext(Context context) {
return context == null ? Context.NONE : context;
}
private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) {
return options == null ? new AnalyzeActionsOptions() : options;
}
private String[] parseActionErrorTarget(String targetReference) {
if (CoreUtils.isNullOrEmpty(targetReference)) {
throw logger.logExceptionAsError(new RuntimeException(
"Expected an error with a target field referencing an action but did not get one"));
}
final Matcher matcher = PATTERN.matcher(targetReference);
String[] taskNameIdPair = new String[2];
while (matcher.find()) {
taskNameIdPair[0] = matcher.group(1);
taskNameIdPair[1] = matcher.group(2);
}
return taskNameIdPair;
}
} |
Make this into a class level static `Pattern` | public static int[] parseRefPointerToIndexArray(String assessmentPointer) {
final String patternRegex = "
final Pattern pattern = Pattern.compile(patternRegex);
final Matcher matcher = pattern.matcher(assessmentPointer);
final boolean isMatched = matcher.find();
final int[] result = new int[3];
if (isMatched) {
String[] segments = assessmentPointer.split("/");
result[0] = Integer.parseInt(segments[2]);
result[1] = Integer.parseInt(segments[4]);
result[2] = Integer.parseInt(segments[6]);
} else {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("'%s' is not a valid assessment pointer.", assessmentPointer)));
}
return result;
} | final Pattern pattern = Pattern.compile(patternRegex); | public static int[] parseRefPointerToIndexArray(String assessmentPointer) {
final Matcher matcher = PATTERN.matcher(assessmentPointer);
final boolean isMatched = matcher.find();
final int[] result = new int[3];
if (isMatched) {
result[0] = Integer.parseInt(matcher.group(1));
result[1] = Integer.parseInt(matcher.group(2));
result[2] = Integer.parseInt(matcher.group(3));
} else {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("'%s' is not a valid assessment pointer.", assessmentPointer)));
}
return result;
} | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private static final int NEUTRAL_SCORE_ZERO = 0;
public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(5);
private Utility() {
}
/**
* Verify that list of documents are not null or empty. Otherwise, throw exception.
*
* @param documents A list of documents.
*
* @throws NullPointerException if {@code documents} is null.
* @throws IllegalArgumentException if {@code documents} is empty.
*/
public static void inputDocumentsValidation(Iterable<?> documents) {
Objects.requireNonNull(documents, "'documents' cannot be null.");
final Iterator<?> iterator = documents.iterator();
if (!iterator.hasNext()) {
throw new IllegalArgumentException("'documents' cannot be empty.");
}
}
/**
* Mapping a {@link ErrorResponseException} to {@link HttpResponseException} if exist. Otherwise, return
* original {@link Throwable}.
*
* @param throwable A {@link Throwable}.
* @return A {@link HttpResponseException} or the original throwable type.
*/
public static Throwable mapToHttpResponseExceptionIfExists(Throwable throwable) {
if (throwable instanceof ErrorResponseException) {
ErrorResponseException errorException = (ErrorResponseException) throwable;
final ErrorResponse errorResponse = errorException.getValue();
com.azure.ai.textanalytics.models.TextAnalyticsError textAnalyticsError = null;
if (errorResponse != null && errorResponse.getError() != null) {
textAnalyticsError = toTextAnalyticsError(errorResponse.getError());
}
return new HttpResponseException(errorException.getMessage(), errorException.getResponse(),
textAnalyticsError);
}
return throwable;
}
/**
* Given a list of documents will apply the indexing function to it and return the updated list.
*
* @param documents the inputs to apply the mapping function to.
* @param mappingFunction the function which applies the index to the incoming input value.
* @param <T> the type of items being returned in the list.
* @return The list holding all the generic items combined.
*/
public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) {
Objects.requireNonNull(documents, "'documents' cannot be null.");
AtomicInteger i = new AtomicInteger(0);
List<T> result = new ArrayList<>();
documents.forEach(document ->
result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document))
);
return result;
}
/**
* Convert {@link DocumentStatistics} to {@link TextDocumentStatistics}
*
* @param statistics the {@link DocumentStatistics} provided by the service.
* @return the {@link TextDocumentStatistics} returned by the SDK.
*/
public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) {
return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount());
}
/**
* Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics}
*
* @param statistics the {@link RequestStatistics} provided by the service.
* @return the {@link TextDocumentBatchStatistics} returned by the SDK.
*/
public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) {
return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(),
statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount());
}
/**
* Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError}
* This function maps the service returned {@link TextAnalyticsError inner error} to the top level
* {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present.
*
* @param textAnalyticsError the {@link TextAnalyticsError} returned by the service.
* @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK.
*/
public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError(
TextAnalyticsError textAnalyticsError) {
final InnerError innerError = textAnalyticsError.getInnererror();
if (innerError == null) {
final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode();
return new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()),
textAnalyticsError.getMessage(),
textAnalyticsError.getTarget());
}
final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode();
return new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()),
innerError.getMessage(),
innerError.getTarget());
}
/**
* Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}.
*
* @param documents the user provided input in {@link TextDocumentInput}
* @return the service required input {@link MultiLanguageInput}
*/
public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) {
List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>();
for (TextDocumentInput textDocumentInput : documents) {
multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId())
.setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage()));
}
return multiLanguageInputs;
}
/**
* Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError}
* to a {@link TextAnalyticsException}.
*
* @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}.
* @return the {@link TextAnalyticsException} to be thrown.
*/
public static TextAnalyticsException toTextAnalyticsException(
com.azure.ai.textanalytics.models.TextAnalyticsError error) {
return new TextAnalyticsException(error.getMessage(), error.getErrorCode(), error.getTarget());
}
/**
* Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}.
*
* @param documents The list of documents to detect languages for.
*
* @return a list of {@link LanguageInput}.
*/
public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) {
final List<LanguageInput> multiLanguageInputs = new ArrayList<>();
documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput()
.setId(textDocumentInput.getId())
.setText(textDocumentInput.getText())
.setCountryHint(textDocumentInput.getCountryHint())));
return multiLanguageInputs;
}
/**
* Extracts the operation ID from the 'operation-location' URL. An example of 'operation-location' is
* https:
*
* @param operationLocation The URL specified in the 'Operation-Location' response header containing the
* operation ID used to track the progress and obtain the ID of the analyze operation.
*
* @return The operation ID that tracks the long running operation progress.
*/
public static String parseOperationId(String operationLocation) {
if (!CoreUtils.isNullOrEmpty(operationLocation)) {
int lastIndex = operationLocation.lastIndexOf('/');
if (lastIndex != -1) {
return operationLocation.substring(lastIndex + 1);
}
}
throw LOGGER.logExceptionAsError(
new RuntimeException("Failed to parse operation header for operation Id from: " + operationLocation));
}
/**
* Extract the next pagination link which contains the request parameter values, into map,
* such as '$skip=20' and '$top=2'.
*
* @param nextLink the next pagination link.
*
* @return A map that holds the request parameter value of next pagination link.
*/
public static Map<String, Object> parseNextLink(String nextLink) {
if (!CoreUtils.isNullOrEmpty(nextLink)) {
final Map<String, Object> parameterMap = new HashMap<>();
final String[] strings = nextLink.split("\\?", 2);
final String[] parameters = strings[1].split("&");
for (String parameter : parameters) {
final String[] parameterPair = parameter.split("=");
final String key = parameterPair[0];
final String value = parameterPair[1];
if ("showStats".equals(key)) {
parameterMap.put(key, value);
} else if ("$skip".equals(key) || "$top".equals(key)) {
parameterMap.put(key, Integer.valueOf(value));
}
}
return parameterMap;
}
return new HashMap<>();
}
public static RecognizeEntitiesResultCollection toRecognizeEntitiesResultCollectionResponse(
final EntitiesResult entitiesResult) {
List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
entitiesResult.getDocuments().forEach(documentEntities ->
recognizeEntitiesResults.add(new RecognizeEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new CategorizedEntityCollection(
new IterableStream<>(documentEntities.getEntities().stream().map(entity -> {
final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(),
EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(),
entity.getConfidenceScore(), entity.getOffset());
CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength());
return categorizedEntity;
}).collect(Collectors.toList())),
new IterableStream<>(documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())))
)));
for (DocumentError documentError : entitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, entitiesResult.getModelVersion(),
entitiesResult.getStatistics() == null ? null : toBatchStatistics(entitiesResult.getStatistics()));
}
public static RecognizePiiEntitiesResultCollection toRecognizePiiEntitiesResultCollection(
final PiiResult piiEntitiesResult) {
final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
piiEntitiesResult.getDocuments().forEach(documentEntities -> {
final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity -> {
final PiiEntity piiEntity = new PiiEntity();
PiiEntityPropertiesHelper.setText(piiEntity, entity.getText());
PiiEntityPropertiesHelper.setCategory(piiEntity, PiiEntityCategory.fromString(entity.getCategory()));
PiiEntityPropertiesHelper.setSubcategory(piiEntity, entity.getSubcategory());
PiiEntityPropertiesHelper.setConfidenceScore(piiEntity, entity.getConfidenceScore());
PiiEntityPropertiesHelper.setOffset(piiEntity, entity.getOffset());
return piiEntity;
}).collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(),
new IterableStream<>(warnings))
));
});
for (DocumentError documentError : piiEntitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(),
piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics()));
}
public static ExtractKeyPhrasesResultCollection toExtractKeyPhrasesResultCollection(
final KeyPhraseResult keyPhraseResult) {
final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>();
for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) {
final String documentId = documentKeyPhrases.getId();
keyPhraseResultList.add(new ExtractKeyPhraseResult(
documentId,
documentKeyPhrases.getStatistics() == null ? null
: toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null,
new KeyPhrasesCollection(
new IterableStream<>(documentKeyPhrases.getKeyPhrases()),
new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())))));
}
for (DocumentError documentError : keyPhraseResult.getErrors()) {
keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(),
keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()));
}
public static Response<RecognizeLinkedEntitiesResultCollection> toRecognizeLinkedEntitiesResultCollectionResponse(
final Response<EntityLinkingResult> response) {
final EntityLinkingResult entityLinkingResult = response.getValue();
return new SimpleResponse<>(response,
new RecognizeLinkedEntitiesResultCollection(toRecognizeLinkedEntitiesResultCollection(entityLinkingResult),
entityLinkingResult.getModelVersion(),
entityLinkingResult.getStatistics() == null ? null
: toBatchStatistics(entityLinkingResult.getStatistics())));
}
public static RecognizeLinkedEntitiesResultCollection toRecognizeLinkedEntitiesResultCollection(
final EntityLinkingResult entityLinkingResult) {
final List<RecognizeLinkedEntitiesResult> linkedEntitiesResults =
entityLinkingResult.getDocuments().stream().map(
documentLinkedEntities -> new RecognizeLinkedEntitiesResult(
documentLinkedEntities.getId(),
documentLinkedEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentLinkedEntities.getStatistics()),
null,
new LinkedEntityCollection(new IterableStream<>(
documentLinkedEntities.getEntities().stream().map(
linkedEntity -> new LinkedEntity(
linkedEntity.getName(),
new IterableStream<>(
linkedEntity.getMatches().stream().map(
match -> {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch(
match.getText(), match.getConfidenceScore(), match.getOffset());
LinkedEntityMatchPropertiesHelper.setLength(linkedEntityMatch,
match.getLength());
return linkedEntityMatch;
}).collect(Collectors.toList())),
linkedEntity.getLanguage(),
linkedEntity.getId(),
linkedEntity.getUrl(),
linkedEntity.getDataSource(),
linkedEntity.getBingId())).collect(Collectors.toList())),
new IterableStream<>(documentLinkedEntities.getWarnings().stream().map(
warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null
: warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())
)
)
)
).collect(Collectors.toList());
for (DocumentError documentError : entityLinkingResult.getErrors()) {
linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizeLinkedEntitiesResultCollection(linkedEntitiesResults, entityLinkingResult.getModelVersion(),
entityLinkingResult.getStatistics() == null ? null
: toBatchStatistics(entityLinkingResult.getStatistics()));
}
/**
* Transfer {@link HealthcareResult} into {@link IterableStream} of {@link AnalyzeHealthcareEntitiesResult}.
*
* @param healthcareResult the service side raw data, HealthcareResult.
*
* @return the client side explored model, RecognizeHealthcareEntitiesResultCollection.
*/
public static IterableStream<AnalyzeHealthcareEntitiesResult> toRecognizeHealthcareEntitiesResults(
HealthcareResult healthcareResult) {
List<AnalyzeHealthcareEntitiesResult> analyzeHealthcareEntitiesResults = new ArrayList<>();
healthcareResult.getDocuments().forEach(
documentEntities -> {
final AnalyzeHealthcareEntitiesResult analyzeHealthcareEntitiesResult =
new AnalyzeHealthcareEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null);
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map(
textAnalyticsWarning -> new TextAnalyticsWarning(
Optional.ofNullable(textAnalyticsWarning.getCode())
.map(warningCodeValue -> WarningCode.fromString(warningCodeValue.toString()))
.orElse(null),
textAnalyticsWarning.getMessage())
).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setWarnings(analyzeHealthcareEntitiesResult,
IterableStream.of(warnings));
final List<HealthcareEntity> healthcareEntities = documentEntities.getEntities().stream().map(
entity -> {
final HealthcareEntity healthcareEntity = new HealthcareEntity();
HealthcareEntityPropertiesHelper.setText(healthcareEntity, entity.getText());
HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity, entity.getName());
HealthcareEntityPropertiesHelper.setCategory(healthcareEntity, entity.getCategory());
HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity,
entity.getConfidenceScore());
HealthcareEntityPropertiesHelper.setOffset(healthcareEntity, entity.getOffset());
HealthcareEntityPropertiesHelper.setLength(healthcareEntity, entity.getLength());
final List<EntityDataSource> entityDataSources =
Optional.ofNullable(entity.getLinks()).map(
links -> links.stream().map(
link -> {
final EntityDataSource dataSource = new EntityDataSource();
EntityDataSourcePropertiesHelper.setName(dataSource, link.getDataSource());
EntityDataSourcePropertiesHelper.setEntityId(dataSource, link.getId());
return dataSource;
}
).collect(Collectors.toList()))
.orElse(new ArrayList<>());
HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity,
IterableStream.of(entityDataSources));
final HealthcareAssertion assertion = entity.getAssertion();
if (assertion != null) {
HealthcareEntityPropertiesHelper.setAssertion(healthcareEntity,
toHealthcareEntityAssertion(assertion));
}
return healthcareEntity;
}).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(analyzeHealthcareEntitiesResult,
IterableStream.of(healthcareEntities));
final List<HealthcareEntityRelation> healthcareEntityRelations =
documentEntities.getRelations().stream().map(
healthcareRelation -> {
final HealthcareEntityRelation entityRelation = new HealthcareEntityRelation();
final RelationType relationType = healthcareRelation.getRelationType();
if (relationType != null) {
HealthcareEntityRelationPropertiesHelper.setRelationType(entityRelation,
HealthcareEntityRelationType.fromString(relationType.toString()));
}
final List<HealthcareEntityRelationRole> relationRoles =
healthcareRelation.getEntities().stream().map(
relationEntity -> {
final HealthcareEntityRelationRole relationRole =
new HealthcareEntityRelationRole();
HealthcareEntityRelationRolePropertiesHelper.setName(relationRole,
relationEntity.getRole());
HealthcareEntityRelationRolePropertiesHelper.setEntity(relationRole,
healthcareEntities.get(getHealthcareEntityIndex(relationEntity.getRef())));
return relationRole;
}).collect(Collectors.toList());
HealthcareEntityRelationPropertiesHelper.setRoles(entityRelation,
IterableStream.of(relationRoles));
return entityRelation;
}).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(analyzeHealthcareEntitiesResult,
IterableStream.of(healthcareEntityRelations));
analyzeHealthcareEntitiesResults.add(analyzeHealthcareEntitiesResult);
});
healthcareResult.getErrors().forEach(documentError ->
analyzeHealthcareEntitiesResults.add(new AnalyzeHealthcareEntitiesResult(
documentError.getId(),
null,
toTextAnalyticsError(documentError.getError())))
);
return IterableStream.of(analyzeHealthcareEntitiesResults);
}
public static HealthcareEntityAssertion toHealthcareEntityAssertion(HealthcareAssertion healthcareAssertion) {
final Association association = healthcareAssertion.getAssociation();
final Certainty certainty = healthcareAssertion.getCertainty();
final Conditionality conditionality = healthcareAssertion.getConditionality();
final HealthcareEntityAssertion entityAssertion = new HealthcareEntityAssertion();
if (association != null) {
HealthcareEntityAssertionPropertiesHelper.setAssociation(entityAssertion,
EntityAssociation.fromString(association.toString()));
}
if (certainty != null) {
HealthcareEntityAssertionPropertiesHelper.setCertainty(entityAssertion,
toCertainty(certainty));
}
if (conditionality != null) {
HealthcareEntityAssertionPropertiesHelper.setConditionality(entityAssertion,
toConditionality(conditionality));
}
return entityAssertion;
}
private static EntityCertainty toCertainty(Certainty certainty) {
EntityCertainty entityCertainty1 = null;
switch (certainty) {
case POSITIVE:
entityCertainty1 = EntityCertainty.POSITIVE;
break;
case POSITIVE_POSSIBLE:
entityCertainty1 = EntityCertainty.POSITIVE_POSSIBLE;
break;
case NEUTRAL_POSSIBLE:
entityCertainty1 = EntityCertainty.NEUTRAL_POSSIBLE;
break;
case NEGATIVE_POSSIBLE:
entityCertainty1 = EntityCertainty.NEGATIVE_POSSIBLE;
break;
case NEGATIVE:
entityCertainty1 = EntityCertainty.NEGATIVE;
break;
default:
break;
}
return entityCertainty1;
}
private static EntityConditionality toConditionality(Conditionality conditionality) {
EntityConditionality conditionality1 = null;
switch (conditionality) {
case HYPOTHETICAL:
conditionality1 = EntityConditionality.HYPOTHETICAL;
break;
case CONDITIONAL:
conditionality1 = EntityConditionality.CONDITIONAL;
break;
default:
break;
}
return conditionality1;
}
/**
* Helper function that parse healthcare entity index from the given entity reference string.
* The entity reference format is "
*
* @param entityReference the given healthcare entity reference string.
*
* @return the healthcare entity index.
*/
private static Integer getHealthcareEntityIndex(String entityReference) {
if (!CoreUtils.isNullOrEmpty(entityReference)) {
int lastIndex = entityReference.lastIndexOf('/');
if (lastIndex != -1) {
return Integer.parseInt(entityReference.substring(lastIndex + 1));
}
}
throw LOGGER.logExceptionAsError(
new RuntimeException("Failed to parse healthcare entity index from: " + entityReference));
}
/**
* Transfer {@link com.azure.ai.textanalytics.models.StringIndexType} into auto-generated {@link StringIndexType}.
* If value is null, use the default type for java, UTF16CODE_UNIT.
*
* @param stringIndexType The public explored StringIndexType.
*
* @return The autogenerated internally used StringIndexType.
*/
public static StringIndexType getNonNullStringIndexType(
com.azure.ai.textanalytics.models.StringIndexType stringIndexType) {
return stringIndexType == null ? StringIndexType.UTF16CODE_UNIT
: StringIndexType.fromString(stringIndexType.toString());
}
/**
* Get the non-null {@link Context}. The default value is {@link Context
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context getNotNullContext(Context context) {
return context == null ? Context.NONE : context;
}
/**
* Helper function which retrieves the size of an {@link Iterable}.
*
* @param documents The iterable of documents.
* @return Count of documents in the iterable.
*/
public static int getDocumentCount(Iterable<?> documents) {
if (documents instanceof Collection) {
return ((Collection<?>) documents).size();
} else {
final int[] count = new int[] { 0 };
documents.forEach(ignored -> count[0] += 1);
return count[0];
}
}
/**
* Helper function which convert the {@code Iterable<PiiEntityCategory>} to {@code List<PiiCategory>}.
*
* @param categoriesFilter the iterable of {@link PiiEntityCategory}.
* @return the list of {@link PiiCategory}.
*/
public static List<PiiCategory> toCategoriesFilter(Iterable<PiiEntityCategory> categoriesFilter) {
if (categoriesFilter == null) {
return null;
}
final List<PiiCategory> piiCategories = new ArrayList<>();
categoriesFilter.forEach(category -> piiCategories.add(PiiCategory.fromString(category.toString())));
return piiCategories;
}
/**
* Helper method to convert {@link SentimentResponse} to {@link AnalyzeSentimentResultCollection}.
*
* @param sentimentResponse The {@link SentimentResponse}.
*
* @return A {@link AnalyzeSentimentResultCollection}.
*/
public static AnalyzeSentimentResultCollection toAnalyzeSentimentResultCollection(
SentimentResponse sentimentResponse) {
final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>();
final List<DocumentSentiment> documentSentiments = sentimentResponse.getDocuments();
for (DocumentSentiment documentSentiment : documentSentiments) {
analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment, documentSentiments));
}
for (DocumentError documentError : sentimentResponse.getErrors()) {
analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(),
sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics()));
}
/**
* Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}.
*
* @param documentSentiment The {@link DocumentSentiment} returned by the service.
* @param documentSentimentList The document sentiment list returned by the service.
*
* @return The {@link AnalyzeSentimentResult} to be returned by the SDK.
*/
private static AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment,
List<DocumentSentiment> documentSentimentList) {
final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores();
final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream()
.map(sentenceSentiment -> {
final SentimentConfidenceScorePerLabel confidenceScorePerSentence =
sentenceSentiment.getConfidenceScores();
final SentenceSentimentValue sentenceSentimentValue = sentenceSentiment.getSentiment();
final SentenceSentiment sentenceSentiment1 = new SentenceSentiment(sentenceSentiment.getText(),
TextSentiment.fromString(sentenceSentimentValue == null ? null : sentenceSentimentValue.toString()),
new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(),
confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive()));
SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1,
toSentenceOpinionList(sentenceSentiment, documentSentimentList));
SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, sentenceSentiment.getOffset());
SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, sentenceSentiment.getLength());
return sentenceSentiment1;
}).collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map(
warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
final DocumentSentimentValue documentSentimentValue = documentSentiment.getSentiment();
return new AnalyzeSentimentResult(
documentSentiment.getId(),
documentSentiment.getStatistics() == null
? null : toTextDocumentStatistics(documentSentiment.getStatistics()),
null,
new com.azure.ai.textanalytics.models.DocumentSentiment(
TextSentiment.fromString(documentSentimentValue == null ? null : documentSentimentValue.toString()),
new SentimentConfidenceScores(
confidenceScorePerLabel.getNegative(),
confidenceScorePerLabel.getNeutral(),
confidenceScorePerLabel.getPositive()),
new IterableStream<>(sentenceSentiments),
new IterableStream<>(warnings)));
}
/*
* Transform SentenceSentiment's opinion mining to output that user can use.
*/
private static IterableStream<SentenceOpinion> toSentenceOpinionList(
com.azure.ai.textanalytics.implementation.models.SentenceSentiment sentenceSentiment,
List<DocumentSentiment> documentSentimentList) {
final List<SentenceTarget> sentenceTargets = sentenceSentiment.getTargets();
if (sentenceTargets == null) {
return null;
}
final List<SentenceOpinion> sentenceOpinions = new ArrayList<>();
sentenceTargets.forEach(sentenceTarget -> {
final List<AssessmentSentiment> assessmentSentiments = new ArrayList<>();
sentenceTarget.getRelations().forEach(targetRelation -> {
final TargetRelationType targetRelationType = targetRelation.getRelationType();
final String opinionPointer = targetRelation.getRef();
if (TargetRelationType.ASSESSMENT == targetRelationType) {
assessmentSentiments.add(toAssessmentSentiment(
findSentimentAssessment(opinionPointer, documentSentimentList)));
}
});
final TargetSentiment targetSentiment = new TargetSentiment();
TargetSentimentPropertiesHelper.setText(targetSentiment, sentenceTarget.getText());
TargetSentimentPropertiesHelper.setSentiment(targetSentiment,
TextSentiment.fromString(sentenceTarget.getSentiment().toString()));
TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment,
toSentimentConfidenceScores(sentenceTarget.getConfidenceScores()));
TargetSentimentPropertiesHelper.setOffset(targetSentiment, sentenceTarget.getOffset());
TargetSentimentPropertiesHelper.setLength(targetSentiment, sentenceTarget.getLength());
final SentenceOpinion sentenceOpinion = new SentenceOpinion();
SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion, targetSentiment);
SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion, new IterableStream<>(assessmentSentiments));
sentenceOpinions.add(sentenceOpinion);
});
return new IterableStream<>(sentenceOpinions);
}
/*
* Transform type TargetConfidenceScoreLabel to SentimentConfidenceScores.
*/
private static SentimentConfidenceScores toSentimentConfidenceScores(
TargetConfidenceScoreLabel targetConfidenceScoreLabel) {
return new SentimentConfidenceScores(targetConfidenceScoreLabel.getNegative(), NEUTRAL_SCORE_ZERO,
targetConfidenceScoreLabel.getPositive());
}
/*
* Transform type SentenceOpinion to OpinionSentiment.
*/
private static AssessmentSentiment toAssessmentSentiment(SentenceAssessment sentenceAssessment) {
final AssessmentSentiment assessmentSentiment = new AssessmentSentiment();
AssessmentSentimentPropertiesHelper.setText(assessmentSentiment, sentenceAssessment.getText());
AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment,
TextSentiment.fromString(sentenceAssessment.getSentiment().toString()));
AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment,
toSentimentConfidenceScores(sentenceAssessment.getConfidenceScores()));
AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment, sentenceAssessment.isNegated());
AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment, sentenceAssessment.getOffset());
AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment, sentenceAssessment.getLength());
return assessmentSentiment;
}
/*
* Parses the reference pointer to an index array that contains document, sentence, and opinion indexes.
*/
/*
* Find the specific sentence assessment in the document sentiment list by given the assessment reference pointer.
*/
public static SentenceAssessment findSentimentAssessment(String assessmentPointer,
List<DocumentSentiment> documentSentiments) {
final int[] assessmentIndexes = parseRefPointerToIndexArray(assessmentPointer);
final int documentIndex = assessmentIndexes[0];
final int sentenceIndex = assessmentIndexes[1];
final int assessmentIndex = assessmentIndexes[2];
if (documentIndex >= documentSentiments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid document index '%s' in '%s'.", documentIndex, assessmentPointer)));
}
final DocumentSentiment documentsentiment = documentSentiments.get(documentIndex);
final List<com.azure.ai.textanalytics.implementation.models.SentenceSentiment> sentenceSentiments =
documentsentiment.getSentences();
if (sentenceIndex >= sentenceSentiments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid sentence index '%s' in '%s'.", sentenceIndex, assessmentPointer)));
}
final List<SentenceAssessment> assessments = sentenceSentiments.get(sentenceIndex).getAssessments();
if (assessmentIndex >= assessments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid assessment index '%s' in '%s'.", assessmentIndex, assessmentPointer)));
}
return assessments.get(assessmentIndex);
}
} | class Utility {
public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(5);
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private static final int NEUTRAL_SCORE_ZERO = 0;
private static final String DOCUMENT_SENTENCES_ASSESSMENTS_REG_EXP =
"
private static final Pattern PATTERN;
static {
PATTERN = Pattern.compile(DOCUMENT_SENTENCES_ASSESSMENTS_REG_EXP);
}
private Utility() {
}
/**
* Verify that list of documents are not null or empty. Otherwise, throw exception.
*
* @param documents A list of documents.
*
* @throws NullPointerException if {@code documents} is null.
* @throws IllegalArgumentException if {@code documents} is empty.
*/
public static void inputDocumentsValidation(Iterable<?> documents) {
Objects.requireNonNull(documents, "'documents' cannot be null.");
final Iterator<?> iterator = documents.iterator();
if (!iterator.hasNext()) {
throw new IllegalArgumentException("'documents' cannot be empty.");
}
}
/**
* Mapping a {@link ErrorResponseException} to {@link HttpResponseException} if exist. Otherwise, return
* original {@link Throwable}.
*
* @param throwable A {@link Throwable}.
* @return A {@link HttpResponseException} or the original throwable type.
*/
public static Throwable mapToHttpResponseExceptionIfExists(Throwable throwable) {
if (throwable instanceof ErrorResponseException) {
ErrorResponseException errorException = (ErrorResponseException) throwable;
final ErrorResponse errorResponse = errorException.getValue();
com.azure.ai.textanalytics.models.TextAnalyticsError textAnalyticsError = null;
if (errorResponse != null && errorResponse.getError() != null) {
textAnalyticsError = toTextAnalyticsError(errorResponse.getError());
}
return new HttpResponseException(errorException.getMessage(), errorException.getResponse(),
textAnalyticsError);
}
return throwable;
}
/**
* Given a list of documents will apply the indexing function to it and return the updated list.
*
* @param documents the inputs to apply the mapping function to.
* @param mappingFunction the function which applies the index to the incoming input value.
* @param <T> the type of items being returned in the list.
* @return The list holding all the generic items combined.
*/
public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) {
Objects.requireNonNull(documents, "'documents' cannot be null.");
AtomicInteger i = new AtomicInteger(0);
List<T> result = new ArrayList<>();
documents.forEach(document ->
result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document))
);
return result;
}
/**
* Convert {@link DocumentStatistics} to {@link TextDocumentStatistics}
*
* @param statistics the {@link DocumentStatistics} provided by the service.
* @return the {@link TextDocumentStatistics} returned by the SDK.
*/
public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) {
return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount());
}
/**
* Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics}
*
* @param statistics the {@link RequestStatistics} provided by the service.
* @return the {@link TextDocumentBatchStatistics} returned by the SDK.
*/
public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) {
return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(),
statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount());
}
/**
* Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError}
* This function maps the service returned {@link TextAnalyticsError inner error} to the top level
* {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present.
*
* @param textAnalyticsError the {@link TextAnalyticsError} returned by the service.
* @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK.
*/
public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError(
TextAnalyticsError textAnalyticsError) {
final InnerError innerError = textAnalyticsError.getInnererror();
if (innerError == null) {
final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode();
return new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()),
textAnalyticsError.getMessage(),
textAnalyticsError.getTarget());
}
final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode();
return new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()),
innerError.getMessage(),
innerError.getTarget());
}
/**
* Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}.
*
* @param documents the user provided input in {@link TextDocumentInput}
* @return the service required input {@link MultiLanguageInput}
*/
public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) {
List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>();
for (TextDocumentInput textDocumentInput : documents) {
multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId())
.setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage()));
}
return multiLanguageInputs;
}
/**
* Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError}
* to a {@link TextAnalyticsException}.
*
* @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}.
* @return the {@link TextAnalyticsException} to be thrown.
*/
public static TextAnalyticsException toTextAnalyticsException(
com.azure.ai.textanalytics.models.TextAnalyticsError error) {
return new TextAnalyticsException(error.getMessage(), error.getErrorCode(), error.getTarget());
}
/**
* Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}.
*
* @param documents The list of documents to detect languages for.
*
* @return a list of {@link LanguageInput}.
*/
public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) {
final List<LanguageInput> multiLanguageInputs = new ArrayList<>();
documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput()
.setId(textDocumentInput.getId())
.setText(textDocumentInput.getText())
.setCountryHint(textDocumentInput.getCountryHint())));
return multiLanguageInputs;
}
/**
* Extracts the operation ID from the 'operation-location' URL. An example of 'operation-location' is
* https:
*
* @param operationLocation The URL specified in the 'Operation-Location' response header containing the
* operation ID used to track the progress and obtain the ID of the analyze operation.
*
* @return The operation ID that tracks the long running operation progress.
*/
public static String parseOperationId(String operationLocation) {
if (!CoreUtils.isNullOrEmpty(operationLocation)) {
int lastIndex = operationLocation.lastIndexOf('/');
if (lastIndex != -1) {
return operationLocation.substring(lastIndex + 1);
}
}
throw LOGGER.logExceptionAsError(
new RuntimeException("Failed to parse operation header for operation Id from: " + operationLocation));
}
/**
* Extract the next pagination link which contains the request parameter values, into map,
* such as '$skip=20' and '$top=2'.
*
* @param nextLink the next pagination link.
*
* @return A map that holds the request parameter value of next pagination link.
*/
public static Map<String, Object> parseNextLink(String nextLink) {
if (!CoreUtils.isNullOrEmpty(nextLink)) {
final Map<String, Object> parameterMap = new HashMap<>();
final String[] strings = nextLink.split("\\?", 2);
final String[] parameters = strings[1].split("&");
for (String parameter : parameters) {
final String[] parameterPair = parameter.split("=");
final String key = parameterPair[0];
final String value = parameterPair[1];
if ("showStats".equals(key)) {
parameterMap.put(key, value);
} else if ("$skip".equals(key) || "$top".equals(key)) {
parameterMap.put(key, Integer.valueOf(value));
}
}
return parameterMap;
}
return new HashMap<>();
}
public static RecognizeEntitiesResultCollection toRecognizeEntitiesResultCollectionResponse(
final EntitiesResult entitiesResult) {
List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
entitiesResult.getDocuments().forEach(documentEntities ->
recognizeEntitiesResults.add(new RecognizeEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new CategorizedEntityCollection(
new IterableStream<>(documentEntities.getEntities().stream().map(entity -> {
final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(),
EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(),
entity.getConfidenceScore(), entity.getOffset());
CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength());
return categorizedEntity;
}).collect(Collectors.toList())),
new IterableStream<>(documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())))
)));
for (DocumentError documentError : entitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, entitiesResult.getModelVersion(),
entitiesResult.getStatistics() == null ? null : toBatchStatistics(entitiesResult.getStatistics()));
}
public static RecognizePiiEntitiesResultCollection toRecognizePiiEntitiesResultCollection(
final PiiResult piiEntitiesResult) {
final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
piiEntitiesResult.getDocuments().forEach(documentEntities -> {
final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity -> {
final PiiEntity piiEntity = new PiiEntity();
PiiEntityPropertiesHelper.setText(piiEntity, entity.getText());
PiiEntityPropertiesHelper.setCategory(piiEntity, PiiEntityCategory.fromString(entity.getCategory()));
PiiEntityPropertiesHelper.setSubcategory(piiEntity, entity.getSubcategory());
PiiEntityPropertiesHelper.setConfidenceScore(piiEntity, entity.getConfidenceScore());
PiiEntityPropertiesHelper.setOffset(piiEntity, entity.getOffset());
return piiEntity;
}).collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(),
new IterableStream<>(warnings))
));
});
for (DocumentError documentError : piiEntitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(),
piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics()));
}
public static ExtractKeyPhrasesResultCollection toExtractKeyPhrasesResultCollection(
final KeyPhraseResult keyPhraseResult) {
final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>();
for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) {
final String documentId = documentKeyPhrases.getId();
keyPhraseResultList.add(new ExtractKeyPhraseResult(
documentId,
documentKeyPhrases.getStatistics() == null ? null
: toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null,
new KeyPhrasesCollection(
new IterableStream<>(documentKeyPhrases.getKeyPhrases()),
new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())))));
}
for (DocumentError documentError : keyPhraseResult.getErrors()) {
keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(),
keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()));
}
public static Response<RecognizeLinkedEntitiesResultCollection> toRecognizeLinkedEntitiesResultCollectionResponse(
final Response<EntityLinkingResult> response) {
final EntityLinkingResult entityLinkingResult = response.getValue();
return new SimpleResponse<>(response,
new RecognizeLinkedEntitiesResultCollection(toRecognizeLinkedEntitiesResultCollection(entityLinkingResult),
entityLinkingResult.getModelVersion(),
entityLinkingResult.getStatistics() == null ? null
: toBatchStatistics(entityLinkingResult.getStatistics())));
}
public static RecognizeLinkedEntitiesResultCollection toRecognizeLinkedEntitiesResultCollection(
final EntityLinkingResult entityLinkingResult) {
final List<RecognizeLinkedEntitiesResult> linkedEntitiesResults =
entityLinkingResult.getDocuments().stream().map(
documentLinkedEntities -> new RecognizeLinkedEntitiesResult(
documentLinkedEntities.getId(),
documentLinkedEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentLinkedEntities.getStatistics()),
null,
new LinkedEntityCollection(new IterableStream<>(
documentLinkedEntities.getEntities().stream().map(
linkedEntity -> new LinkedEntity(
linkedEntity.getName(),
new IterableStream<>(
linkedEntity.getMatches().stream().map(
match -> {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch(
match.getText(), match.getConfidenceScore(), match.getOffset());
LinkedEntityMatchPropertiesHelper.setLength(linkedEntityMatch,
match.getLength());
return linkedEntityMatch;
}).collect(Collectors.toList())),
linkedEntity.getLanguage(),
linkedEntity.getId(),
linkedEntity.getUrl(),
linkedEntity.getDataSource(),
linkedEntity.getBingId())).collect(Collectors.toList())),
new IterableStream<>(documentLinkedEntities.getWarnings().stream().map(
warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null
: warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())
)
)
)
).collect(Collectors.toList());
for (DocumentError documentError : entityLinkingResult.getErrors()) {
linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizeLinkedEntitiesResultCollection(linkedEntitiesResults, entityLinkingResult.getModelVersion(),
entityLinkingResult.getStatistics() == null ? null
: toBatchStatistics(entityLinkingResult.getStatistics()));
}
/**
* Transfer {@link HealthcareResult} into {@link IterableStream} of {@link AnalyzeHealthcareEntitiesResult}.
*
* @param healthcareResult the service side raw data, HealthcareResult.
*
* @return the client side explored model, RecognizeHealthcareEntitiesResultCollection.
*/
public static IterableStream<AnalyzeHealthcareEntitiesResult> toRecognizeHealthcareEntitiesResults(
HealthcareResult healthcareResult) {
List<AnalyzeHealthcareEntitiesResult> analyzeHealthcareEntitiesResults = new ArrayList<>();
healthcareResult.getDocuments().forEach(
documentEntities -> {
final AnalyzeHealthcareEntitiesResult analyzeHealthcareEntitiesResult =
new AnalyzeHealthcareEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null);
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map(
textAnalyticsWarning -> new TextAnalyticsWarning(
Optional.ofNullable(textAnalyticsWarning.getCode())
.map(warningCodeValue -> WarningCode.fromString(warningCodeValue.toString()))
.orElse(null),
textAnalyticsWarning.getMessage())
).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setWarnings(analyzeHealthcareEntitiesResult,
IterableStream.of(warnings));
final List<HealthcareEntity> healthcareEntities = documentEntities.getEntities().stream().map(
entity -> {
final HealthcareEntity healthcareEntity = new HealthcareEntity();
HealthcareEntityPropertiesHelper.setText(healthcareEntity, entity.getText());
HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity, entity.getName());
HealthcareEntityPropertiesHelper.setCategory(healthcareEntity, entity.getCategory());
HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity,
entity.getConfidenceScore());
HealthcareEntityPropertiesHelper.setOffset(healthcareEntity, entity.getOffset());
HealthcareEntityPropertiesHelper.setLength(healthcareEntity, entity.getLength());
final List<EntityDataSource> entityDataSources =
Optional.ofNullable(entity.getLinks()).map(
links -> links.stream().map(
link -> {
final EntityDataSource dataSource = new EntityDataSource();
EntityDataSourcePropertiesHelper.setName(dataSource, link.getDataSource());
EntityDataSourcePropertiesHelper.setEntityId(dataSource, link.getId());
return dataSource;
}
).collect(Collectors.toList()))
.orElse(new ArrayList<>());
HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity,
IterableStream.of(entityDataSources));
final HealthcareAssertion assertion = entity.getAssertion();
if (assertion != null) {
HealthcareEntityPropertiesHelper.setAssertion(healthcareEntity,
toHealthcareEntityAssertion(assertion));
}
return healthcareEntity;
}).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(analyzeHealthcareEntitiesResult,
IterableStream.of(healthcareEntities));
final List<HealthcareEntityRelation> healthcareEntityRelations =
documentEntities.getRelations().stream().map(
healthcareRelation -> {
final HealthcareEntityRelation entityRelation = new HealthcareEntityRelation();
final RelationType relationType = healthcareRelation.getRelationType();
if (relationType != null) {
HealthcareEntityRelationPropertiesHelper.setRelationType(entityRelation,
HealthcareEntityRelationType.fromString(relationType.toString()));
}
final List<HealthcareEntityRelationRole> relationRoles =
healthcareRelation.getEntities().stream().map(
relationEntity -> {
final HealthcareEntityRelationRole relationRole =
new HealthcareEntityRelationRole();
HealthcareEntityRelationRolePropertiesHelper.setName(relationRole,
relationEntity.getRole());
HealthcareEntityRelationRolePropertiesHelper.setEntity(relationRole,
healthcareEntities.get(getHealthcareEntityIndex(relationEntity.getRef())));
return relationRole;
}).collect(Collectors.toList());
HealthcareEntityRelationPropertiesHelper.setRoles(entityRelation,
IterableStream.of(relationRoles));
return entityRelation;
}).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(analyzeHealthcareEntitiesResult,
IterableStream.of(healthcareEntityRelations));
analyzeHealthcareEntitiesResults.add(analyzeHealthcareEntitiesResult);
});
healthcareResult.getErrors().forEach(documentError ->
analyzeHealthcareEntitiesResults.add(new AnalyzeHealthcareEntitiesResult(
documentError.getId(),
null,
toTextAnalyticsError(documentError.getError())))
);
return IterableStream.of(analyzeHealthcareEntitiesResults);
}
public static HealthcareEntityAssertion toHealthcareEntityAssertion(HealthcareAssertion healthcareAssertion) {
final Association association = healthcareAssertion.getAssociation();
final Certainty certainty = healthcareAssertion.getCertainty();
final Conditionality conditionality = healthcareAssertion.getConditionality();
final HealthcareEntityAssertion entityAssertion = new HealthcareEntityAssertion();
if (association != null) {
HealthcareEntityAssertionPropertiesHelper.setAssociation(entityAssertion,
EntityAssociation.fromString(association.toString()));
}
if (certainty != null) {
HealthcareEntityAssertionPropertiesHelper.setCertainty(entityAssertion,
toCertainty(certainty));
}
if (conditionality != null) {
HealthcareEntityAssertionPropertiesHelper.setConditionality(entityAssertion,
toConditionality(conditionality));
}
return entityAssertion;
}
private static EntityCertainty toCertainty(Certainty certainty) {
EntityCertainty entityCertainty1 = null;
switch (certainty) {
case POSITIVE:
entityCertainty1 = EntityCertainty.POSITIVE;
break;
case POSITIVE_POSSIBLE:
entityCertainty1 = EntityCertainty.POSITIVE_POSSIBLE;
break;
case NEUTRAL_POSSIBLE:
entityCertainty1 = EntityCertainty.NEUTRAL_POSSIBLE;
break;
case NEGATIVE_POSSIBLE:
entityCertainty1 = EntityCertainty.NEGATIVE_POSSIBLE;
break;
case NEGATIVE:
entityCertainty1 = EntityCertainty.NEGATIVE;
break;
default:
break;
}
return entityCertainty1;
}
private static EntityConditionality toConditionality(Conditionality conditionality) {
EntityConditionality conditionality1 = null;
switch (conditionality) {
case HYPOTHETICAL:
conditionality1 = EntityConditionality.HYPOTHETICAL;
break;
case CONDITIONAL:
conditionality1 = EntityConditionality.CONDITIONAL;
break;
default:
break;
}
return conditionality1;
}
/**
* Helper function that parse healthcare entity index from the given entity reference string.
* The entity reference format is "
*
* @param entityReference the given healthcare entity reference string.
*
* @return the healthcare entity index.
*/
private static Integer getHealthcareEntityIndex(String entityReference) {
if (!CoreUtils.isNullOrEmpty(entityReference)) {
int lastIndex = entityReference.lastIndexOf('/');
if (lastIndex != -1) {
return Integer.parseInt(entityReference.substring(lastIndex + 1));
}
}
throw LOGGER.logExceptionAsError(
new RuntimeException("Failed to parse healthcare entity index from: " + entityReference));
}
/**
* Transfer {@link com.azure.ai.textanalytics.models.StringIndexType} into auto-generated {@link StringIndexType}.
* If value is null, use the default type for java, UTF16CODE_UNIT.
*
* @param stringIndexType The public explored StringIndexType.
*
* @return The autogenerated internally used StringIndexType.
*/
public static StringIndexType getNonNullStringIndexType(
com.azure.ai.textanalytics.models.StringIndexType stringIndexType) {
return stringIndexType == null ? StringIndexType.UTF16CODE_UNIT
: StringIndexType.fromString(stringIndexType.toString());
}
/**
* Get the non-null {@link Context}. The default value is {@link Context
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context getNotNullContext(Context context) {
return context == null ? Context.NONE : context;
}
/**
* Helper function which retrieves the size of an {@link Iterable}.
*
* @param documents The iterable of documents.
* @return Count of documents in the iterable.
*/
public static int getDocumentCount(Iterable<?> documents) {
if (documents instanceof Collection) {
return ((Collection<?>) documents).size();
} else {
final int[] count = new int[] { 0 };
documents.forEach(ignored -> count[0] += 1);
return count[0];
}
}
/**
* Helper function which convert the {@code Iterable<PiiEntityCategory>} to {@code List<PiiCategory>}.
*
* @param categoriesFilter the iterable of {@link PiiEntityCategory}.
* @return the list of {@link PiiCategory}.
*/
public static List<PiiCategory> toCategoriesFilter(Iterable<PiiEntityCategory> categoriesFilter) {
if (categoriesFilter == null) {
return null;
}
final List<PiiCategory> piiCategories = new ArrayList<>();
categoriesFilter.forEach(category -> piiCategories.add(PiiCategory.fromString(category.toString())));
return piiCategories;
}
/**
* Helper method to convert {@link SentimentResponse} to {@link AnalyzeSentimentResultCollection}.
*
* @param sentimentResponse The {@link SentimentResponse}.
*
* @return A {@link AnalyzeSentimentResultCollection}.
*/
public static AnalyzeSentimentResultCollection toAnalyzeSentimentResultCollection(
SentimentResponse sentimentResponse) {
final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>();
final List<DocumentSentiment> documentSentiments = sentimentResponse.getDocuments();
for (DocumentSentiment documentSentiment : documentSentiments) {
analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment, documentSentiments));
}
for (DocumentError documentError : sentimentResponse.getErrors()) {
analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(),
sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics()));
}
/**
* Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}.
*
* @param documentSentiment The {@link DocumentSentiment} returned by the service.
* @param documentSentimentList The document sentiment list returned by the service.
*
* @return The {@link AnalyzeSentimentResult} to be returned by the SDK.
*/
private static AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment,
List<DocumentSentiment> documentSentimentList) {
final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores();
final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream()
.map(sentenceSentiment -> {
final SentimentConfidenceScorePerLabel confidenceScorePerSentence =
sentenceSentiment.getConfidenceScores();
final SentenceSentimentValue sentenceSentimentValue = sentenceSentiment.getSentiment();
final SentenceSentiment sentenceSentiment1 = new SentenceSentiment(sentenceSentiment.getText(),
TextSentiment.fromString(sentenceSentimentValue == null ? null : sentenceSentimentValue.toString()),
new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(),
confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive()));
SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1,
toSentenceOpinionList(sentenceSentiment, documentSentimentList));
SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, sentenceSentiment.getOffset());
SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, sentenceSentiment.getLength());
return sentenceSentiment1;
}).collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map(
warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
final DocumentSentimentValue documentSentimentValue = documentSentiment.getSentiment();
return new AnalyzeSentimentResult(
documentSentiment.getId(),
documentSentiment.getStatistics() == null
? null : toTextDocumentStatistics(documentSentiment.getStatistics()),
null,
new com.azure.ai.textanalytics.models.DocumentSentiment(
TextSentiment.fromString(documentSentimentValue == null ? null : documentSentimentValue.toString()),
new SentimentConfidenceScores(
confidenceScorePerLabel.getNegative(),
confidenceScorePerLabel.getNeutral(),
confidenceScorePerLabel.getPositive()),
new IterableStream<>(sentenceSentiments),
new IterableStream<>(warnings)));
}
/*
* Transform SentenceSentiment's opinion mining to output that user can use.
*/
private static IterableStream<SentenceOpinion> toSentenceOpinionList(
com.azure.ai.textanalytics.implementation.models.SentenceSentiment sentenceSentiment,
List<DocumentSentiment> documentSentimentList) {
final List<SentenceTarget> sentenceTargets = sentenceSentiment.getTargets();
if (sentenceTargets == null) {
return null;
}
final List<SentenceOpinion> sentenceOpinions = new ArrayList<>();
sentenceTargets.forEach(sentenceTarget -> {
final List<AssessmentSentiment> assessmentSentiments = new ArrayList<>();
sentenceTarget.getRelations().forEach(targetRelation -> {
final TargetRelationType targetRelationType = targetRelation.getRelationType();
final String opinionPointer = targetRelation.getRef();
if (TargetRelationType.ASSESSMENT == targetRelationType) {
assessmentSentiments.add(toAssessmentSentiment(
findSentimentAssessment(opinionPointer, documentSentimentList)));
}
});
final TargetSentiment targetSentiment = new TargetSentiment();
TargetSentimentPropertiesHelper.setText(targetSentiment, sentenceTarget.getText());
TargetSentimentPropertiesHelper.setSentiment(targetSentiment,
TextSentiment.fromString(sentenceTarget.getSentiment().toString()));
TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment,
toSentimentConfidenceScores(sentenceTarget.getConfidenceScores()));
TargetSentimentPropertiesHelper.setOffset(targetSentiment, sentenceTarget.getOffset());
TargetSentimentPropertiesHelper.setLength(targetSentiment, sentenceTarget.getLength());
final SentenceOpinion sentenceOpinion = new SentenceOpinion();
SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion, targetSentiment);
SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion, new IterableStream<>(assessmentSentiments));
sentenceOpinions.add(sentenceOpinion);
});
return new IterableStream<>(sentenceOpinions);
}
/*
* Transform type TargetConfidenceScoreLabel to SentimentConfidenceScores.
*/
private static SentimentConfidenceScores toSentimentConfidenceScores(
TargetConfidenceScoreLabel targetConfidenceScoreLabel) {
return new SentimentConfidenceScores(targetConfidenceScoreLabel.getNegative(), NEUTRAL_SCORE_ZERO,
targetConfidenceScoreLabel.getPositive());
}
/*
* Transform type SentenceOpinion to OpinionSentiment.
*/
private static AssessmentSentiment toAssessmentSentiment(SentenceAssessment sentenceAssessment) {
final AssessmentSentiment assessmentSentiment = new AssessmentSentiment();
AssessmentSentimentPropertiesHelper.setText(assessmentSentiment, sentenceAssessment.getText());
AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment,
TextSentiment.fromString(sentenceAssessment.getSentiment().toString()));
AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment,
toSentimentConfidenceScores(sentenceAssessment.getConfidenceScores()));
AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment, sentenceAssessment.isNegated());
AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment, sentenceAssessment.getOffset());
AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment, sentenceAssessment.getLength());
return assessmentSentiment;
}
/*
* Parses the reference pointer to an index array that contains document, sentence, and opinion indexes.
*/
/*
* Find the specific sentence assessment in the document sentiment list by given the assessment reference pointer.
*/
public static SentenceAssessment findSentimentAssessment(String assessmentPointer,
List<DocumentSentiment> documentSentiments) {
final int[] assessmentIndexes = parseRefPointerToIndexArray(assessmentPointer);
final int documentIndex = assessmentIndexes[0];
final int sentenceIndex = assessmentIndexes[1];
final int assessmentIndex = assessmentIndexes[2];
if (documentIndex >= documentSentiments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid document index '%s' in '%s'.", documentIndex, assessmentPointer)));
}
final DocumentSentiment documentsentiment = documentSentiments.get(documentIndex);
final List<com.azure.ai.textanalytics.implementation.models.SentenceSentiment> sentenceSentiments =
documentsentiment.getSentences();
if (sentenceIndex >= sentenceSentiments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid sentence index '%s' in '%s'.", sentenceIndex, assessmentPointer)));
}
final List<SentenceAssessment> assessments = sentenceSentiments.get(sentenceIndex).getAssessments();
if (assessmentIndex >= assessments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid assessment index '%s' in '%s'.", assessmentIndex, assessmentPointer)));
}
return assessments.get(assessmentIndex);
}
} |
No need to do this splitting logic, you're already capturing the numbers in your `Matcher` above. ```java result[0] = Integer.parseInt(matcher.group(1)); result[1] = Integer.parseInt(matcher.group(2)); result[2] = Integer.parseInt(matcher.group(3)); ``` | public static int[] parseRefPointerToIndexArray(String assessmentPointer) {
final String patternRegex = "
final Pattern pattern = Pattern.compile(patternRegex);
final Matcher matcher = pattern.matcher(assessmentPointer);
final boolean isMatched = matcher.find();
final int[] result = new int[3];
if (isMatched) {
String[] segments = assessmentPointer.split("/");
result[0] = Integer.parseInt(segments[2]);
result[1] = Integer.parseInt(segments[4]);
result[2] = Integer.parseInt(segments[6]);
} else {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("'%s' is not a valid assessment pointer.", assessmentPointer)));
}
return result;
} | result[2] = Integer.parseInt(segments[6]); | public static int[] parseRefPointerToIndexArray(String assessmentPointer) {
final Matcher matcher = PATTERN.matcher(assessmentPointer);
final boolean isMatched = matcher.find();
final int[] result = new int[3];
if (isMatched) {
result[0] = Integer.parseInt(matcher.group(1));
result[1] = Integer.parseInt(matcher.group(2));
result[2] = Integer.parseInt(matcher.group(3));
} else {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("'%s' is not a valid assessment pointer.", assessmentPointer)));
}
return result;
} | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private static final int NEUTRAL_SCORE_ZERO = 0;
public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(5);
private Utility() {
}
/**
* Verify that list of documents are not null or empty. Otherwise, throw exception.
*
* @param documents A list of documents.
*
* @throws NullPointerException if {@code documents} is null.
* @throws IllegalArgumentException if {@code documents} is empty.
*/
public static void inputDocumentsValidation(Iterable<?> documents) {
Objects.requireNonNull(documents, "'documents' cannot be null.");
final Iterator<?> iterator = documents.iterator();
if (!iterator.hasNext()) {
throw new IllegalArgumentException("'documents' cannot be empty.");
}
}
/**
* Mapping a {@link ErrorResponseException} to {@link HttpResponseException} if exist. Otherwise, return
* original {@link Throwable}.
*
* @param throwable A {@link Throwable}.
* @return A {@link HttpResponseException} or the original throwable type.
*/
public static Throwable mapToHttpResponseExceptionIfExists(Throwable throwable) {
if (throwable instanceof ErrorResponseException) {
ErrorResponseException errorException = (ErrorResponseException) throwable;
final ErrorResponse errorResponse = errorException.getValue();
com.azure.ai.textanalytics.models.TextAnalyticsError textAnalyticsError = null;
if (errorResponse != null && errorResponse.getError() != null) {
textAnalyticsError = toTextAnalyticsError(errorResponse.getError());
}
return new HttpResponseException(errorException.getMessage(), errorException.getResponse(),
textAnalyticsError);
}
return throwable;
}
/**
* Given a list of documents will apply the indexing function to it and return the updated list.
*
* @param documents the inputs to apply the mapping function to.
* @param mappingFunction the function which applies the index to the incoming input value.
* @param <T> the type of items being returned in the list.
* @return The list holding all the generic items combined.
*/
public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) {
Objects.requireNonNull(documents, "'documents' cannot be null.");
AtomicInteger i = new AtomicInteger(0);
List<T> result = new ArrayList<>();
documents.forEach(document ->
result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document))
);
return result;
}
/**
* Convert {@link DocumentStatistics} to {@link TextDocumentStatistics}
*
* @param statistics the {@link DocumentStatistics} provided by the service.
* @return the {@link TextDocumentStatistics} returned by the SDK.
*/
public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) {
return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount());
}
/**
* Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics}
*
* @param statistics the {@link RequestStatistics} provided by the service.
* @return the {@link TextDocumentBatchStatistics} returned by the SDK.
*/
public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) {
return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(),
statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount());
}
/**
* Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError}
* This function maps the service returned {@link TextAnalyticsError inner error} to the top level
* {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present.
*
* @param textAnalyticsError the {@link TextAnalyticsError} returned by the service.
* @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK.
*/
public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError(
TextAnalyticsError textAnalyticsError) {
final InnerError innerError = textAnalyticsError.getInnererror();
if (innerError == null) {
final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode();
return new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()),
textAnalyticsError.getMessage(),
textAnalyticsError.getTarget());
}
final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode();
return new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()),
innerError.getMessage(),
innerError.getTarget());
}
/**
* Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}.
*
* @param documents the user provided input in {@link TextDocumentInput}
* @return the service required input {@link MultiLanguageInput}
*/
public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) {
List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>();
for (TextDocumentInput textDocumentInput : documents) {
multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId())
.setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage()));
}
return multiLanguageInputs;
}
/**
* Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError}
* to a {@link TextAnalyticsException}.
*
* @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}.
* @return the {@link TextAnalyticsException} to be thrown.
*/
public static TextAnalyticsException toTextAnalyticsException(
com.azure.ai.textanalytics.models.TextAnalyticsError error) {
return new TextAnalyticsException(error.getMessage(), error.getErrorCode(), error.getTarget());
}
/**
* Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}.
*
* @param documents The list of documents to detect languages for.
*
* @return a list of {@link LanguageInput}.
*/
public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) {
final List<LanguageInput> multiLanguageInputs = new ArrayList<>();
documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput()
.setId(textDocumentInput.getId())
.setText(textDocumentInput.getText())
.setCountryHint(textDocumentInput.getCountryHint())));
return multiLanguageInputs;
}
/**
* Extracts the operation ID from the 'operation-location' URL. An example of 'operation-location' is
* https:
*
* @param operationLocation The URL specified in the 'Operation-Location' response header containing the
* operation ID used to track the progress and obtain the ID of the analyze operation.
*
* @return The operation ID that tracks the long running operation progress.
*/
public static String parseOperationId(String operationLocation) {
if (!CoreUtils.isNullOrEmpty(operationLocation)) {
int lastIndex = operationLocation.lastIndexOf('/');
if (lastIndex != -1) {
return operationLocation.substring(lastIndex + 1);
}
}
throw LOGGER.logExceptionAsError(
new RuntimeException("Failed to parse operation header for operation Id from: " + operationLocation));
}
/**
* Extract the next pagination link which contains the request parameter values, into map,
* such as '$skip=20' and '$top=2'.
*
* @param nextLink the next pagination link.
*
* @return A map that holds the request parameter value of next pagination link.
*/
public static Map<String, Object> parseNextLink(String nextLink) {
if (!CoreUtils.isNullOrEmpty(nextLink)) {
final Map<String, Object> parameterMap = new HashMap<>();
final String[] strings = nextLink.split("\\?", 2);
final String[] parameters = strings[1].split("&");
for (String parameter : parameters) {
final String[] parameterPair = parameter.split("=");
final String key = parameterPair[0];
final String value = parameterPair[1];
if ("showStats".equals(key)) {
parameterMap.put(key, value);
} else if ("$skip".equals(key) || "$top".equals(key)) {
parameterMap.put(key, Integer.valueOf(value));
}
}
return parameterMap;
}
return new HashMap<>();
}
public static RecognizeEntitiesResultCollection toRecognizeEntitiesResultCollectionResponse(
final EntitiesResult entitiesResult) {
List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
entitiesResult.getDocuments().forEach(documentEntities ->
recognizeEntitiesResults.add(new RecognizeEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new CategorizedEntityCollection(
new IterableStream<>(documentEntities.getEntities().stream().map(entity -> {
final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(),
EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(),
entity.getConfidenceScore(), entity.getOffset());
CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength());
return categorizedEntity;
}).collect(Collectors.toList())),
new IterableStream<>(documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())))
)));
for (DocumentError documentError : entitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, entitiesResult.getModelVersion(),
entitiesResult.getStatistics() == null ? null : toBatchStatistics(entitiesResult.getStatistics()));
}
public static RecognizePiiEntitiesResultCollection toRecognizePiiEntitiesResultCollection(
final PiiResult piiEntitiesResult) {
final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
piiEntitiesResult.getDocuments().forEach(documentEntities -> {
final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity -> {
final PiiEntity piiEntity = new PiiEntity();
PiiEntityPropertiesHelper.setText(piiEntity, entity.getText());
PiiEntityPropertiesHelper.setCategory(piiEntity, PiiEntityCategory.fromString(entity.getCategory()));
PiiEntityPropertiesHelper.setSubcategory(piiEntity, entity.getSubcategory());
PiiEntityPropertiesHelper.setConfidenceScore(piiEntity, entity.getConfidenceScore());
PiiEntityPropertiesHelper.setOffset(piiEntity, entity.getOffset());
return piiEntity;
}).collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(),
new IterableStream<>(warnings))
));
});
for (DocumentError documentError : piiEntitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(),
piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics()));
}
public static ExtractKeyPhrasesResultCollection toExtractKeyPhrasesResultCollection(
final KeyPhraseResult keyPhraseResult) {
final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>();
for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) {
final String documentId = documentKeyPhrases.getId();
keyPhraseResultList.add(new ExtractKeyPhraseResult(
documentId,
documentKeyPhrases.getStatistics() == null ? null
: toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null,
new KeyPhrasesCollection(
new IterableStream<>(documentKeyPhrases.getKeyPhrases()),
new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())))));
}
for (DocumentError documentError : keyPhraseResult.getErrors()) {
keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(),
keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()));
}
public static Response<RecognizeLinkedEntitiesResultCollection> toRecognizeLinkedEntitiesResultCollectionResponse(
final Response<EntityLinkingResult> response) {
final EntityLinkingResult entityLinkingResult = response.getValue();
return new SimpleResponse<>(response,
new RecognizeLinkedEntitiesResultCollection(toRecognizeLinkedEntitiesResultCollection(entityLinkingResult),
entityLinkingResult.getModelVersion(),
entityLinkingResult.getStatistics() == null ? null
: toBatchStatistics(entityLinkingResult.getStatistics())));
}
public static RecognizeLinkedEntitiesResultCollection toRecognizeLinkedEntitiesResultCollection(
final EntityLinkingResult entityLinkingResult) {
final List<RecognizeLinkedEntitiesResult> linkedEntitiesResults =
entityLinkingResult.getDocuments().stream().map(
documentLinkedEntities -> new RecognizeLinkedEntitiesResult(
documentLinkedEntities.getId(),
documentLinkedEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentLinkedEntities.getStatistics()),
null,
new LinkedEntityCollection(new IterableStream<>(
documentLinkedEntities.getEntities().stream().map(
linkedEntity -> new LinkedEntity(
linkedEntity.getName(),
new IterableStream<>(
linkedEntity.getMatches().stream().map(
match -> {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch(
match.getText(), match.getConfidenceScore(), match.getOffset());
LinkedEntityMatchPropertiesHelper.setLength(linkedEntityMatch,
match.getLength());
return linkedEntityMatch;
}).collect(Collectors.toList())),
linkedEntity.getLanguage(),
linkedEntity.getId(),
linkedEntity.getUrl(),
linkedEntity.getDataSource(),
linkedEntity.getBingId())).collect(Collectors.toList())),
new IterableStream<>(documentLinkedEntities.getWarnings().stream().map(
warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null
: warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())
)
)
)
).collect(Collectors.toList());
for (DocumentError documentError : entityLinkingResult.getErrors()) {
linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizeLinkedEntitiesResultCollection(linkedEntitiesResults, entityLinkingResult.getModelVersion(),
entityLinkingResult.getStatistics() == null ? null
: toBatchStatistics(entityLinkingResult.getStatistics()));
}
/**
* Transfer {@link HealthcareResult} into {@link IterableStream} of {@link AnalyzeHealthcareEntitiesResult}.
*
* @param healthcareResult the service side raw data, HealthcareResult.
*
* @return the client side explored model, RecognizeHealthcareEntitiesResultCollection.
*/
public static IterableStream<AnalyzeHealthcareEntitiesResult> toRecognizeHealthcareEntitiesResults(
HealthcareResult healthcareResult) {
List<AnalyzeHealthcareEntitiesResult> analyzeHealthcareEntitiesResults = new ArrayList<>();
healthcareResult.getDocuments().forEach(
documentEntities -> {
final AnalyzeHealthcareEntitiesResult analyzeHealthcareEntitiesResult =
new AnalyzeHealthcareEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null);
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map(
textAnalyticsWarning -> new TextAnalyticsWarning(
Optional.ofNullable(textAnalyticsWarning.getCode())
.map(warningCodeValue -> WarningCode.fromString(warningCodeValue.toString()))
.orElse(null),
textAnalyticsWarning.getMessage())
).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setWarnings(analyzeHealthcareEntitiesResult,
IterableStream.of(warnings));
final List<HealthcareEntity> healthcareEntities = documentEntities.getEntities().stream().map(
entity -> {
final HealthcareEntity healthcareEntity = new HealthcareEntity();
HealthcareEntityPropertiesHelper.setText(healthcareEntity, entity.getText());
HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity, entity.getName());
HealthcareEntityPropertiesHelper.setCategory(healthcareEntity, entity.getCategory());
HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity,
entity.getConfidenceScore());
HealthcareEntityPropertiesHelper.setOffset(healthcareEntity, entity.getOffset());
HealthcareEntityPropertiesHelper.setLength(healthcareEntity, entity.getLength());
final List<EntityDataSource> entityDataSources =
Optional.ofNullable(entity.getLinks()).map(
links -> links.stream().map(
link -> {
final EntityDataSource dataSource = new EntityDataSource();
EntityDataSourcePropertiesHelper.setName(dataSource, link.getDataSource());
EntityDataSourcePropertiesHelper.setEntityId(dataSource, link.getId());
return dataSource;
}
).collect(Collectors.toList()))
.orElse(new ArrayList<>());
HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity,
IterableStream.of(entityDataSources));
final HealthcareAssertion assertion = entity.getAssertion();
if (assertion != null) {
HealthcareEntityPropertiesHelper.setAssertion(healthcareEntity,
toHealthcareEntityAssertion(assertion));
}
return healthcareEntity;
}).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(analyzeHealthcareEntitiesResult,
IterableStream.of(healthcareEntities));
final List<HealthcareEntityRelation> healthcareEntityRelations =
documentEntities.getRelations().stream().map(
healthcareRelation -> {
final HealthcareEntityRelation entityRelation = new HealthcareEntityRelation();
final RelationType relationType = healthcareRelation.getRelationType();
if (relationType != null) {
HealthcareEntityRelationPropertiesHelper.setRelationType(entityRelation,
HealthcareEntityRelationType.fromString(relationType.toString()));
}
final List<HealthcareEntityRelationRole> relationRoles =
healthcareRelation.getEntities().stream().map(
relationEntity -> {
final HealthcareEntityRelationRole relationRole =
new HealthcareEntityRelationRole();
HealthcareEntityRelationRolePropertiesHelper.setName(relationRole,
relationEntity.getRole());
HealthcareEntityRelationRolePropertiesHelper.setEntity(relationRole,
healthcareEntities.get(getHealthcareEntityIndex(relationEntity.getRef())));
return relationRole;
}).collect(Collectors.toList());
HealthcareEntityRelationPropertiesHelper.setRoles(entityRelation,
IterableStream.of(relationRoles));
return entityRelation;
}).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(analyzeHealthcareEntitiesResult,
IterableStream.of(healthcareEntityRelations));
analyzeHealthcareEntitiesResults.add(analyzeHealthcareEntitiesResult);
});
healthcareResult.getErrors().forEach(documentError ->
analyzeHealthcareEntitiesResults.add(new AnalyzeHealthcareEntitiesResult(
documentError.getId(),
null,
toTextAnalyticsError(documentError.getError())))
);
return IterableStream.of(analyzeHealthcareEntitiesResults);
}
public static HealthcareEntityAssertion toHealthcareEntityAssertion(HealthcareAssertion healthcareAssertion) {
final Association association = healthcareAssertion.getAssociation();
final Certainty certainty = healthcareAssertion.getCertainty();
final Conditionality conditionality = healthcareAssertion.getConditionality();
final HealthcareEntityAssertion entityAssertion = new HealthcareEntityAssertion();
if (association != null) {
HealthcareEntityAssertionPropertiesHelper.setAssociation(entityAssertion,
EntityAssociation.fromString(association.toString()));
}
if (certainty != null) {
HealthcareEntityAssertionPropertiesHelper.setCertainty(entityAssertion,
toCertainty(certainty));
}
if (conditionality != null) {
HealthcareEntityAssertionPropertiesHelper.setConditionality(entityAssertion,
toConditionality(conditionality));
}
return entityAssertion;
}
private static EntityCertainty toCertainty(Certainty certainty) {
EntityCertainty entityCertainty1 = null;
switch (certainty) {
case POSITIVE:
entityCertainty1 = EntityCertainty.POSITIVE;
break;
case POSITIVE_POSSIBLE:
entityCertainty1 = EntityCertainty.POSITIVE_POSSIBLE;
break;
case NEUTRAL_POSSIBLE:
entityCertainty1 = EntityCertainty.NEUTRAL_POSSIBLE;
break;
case NEGATIVE_POSSIBLE:
entityCertainty1 = EntityCertainty.NEGATIVE_POSSIBLE;
break;
case NEGATIVE:
entityCertainty1 = EntityCertainty.NEGATIVE;
break;
default:
break;
}
return entityCertainty1;
}
private static EntityConditionality toConditionality(Conditionality conditionality) {
EntityConditionality conditionality1 = null;
switch (conditionality) {
case HYPOTHETICAL:
conditionality1 = EntityConditionality.HYPOTHETICAL;
break;
case CONDITIONAL:
conditionality1 = EntityConditionality.CONDITIONAL;
break;
default:
break;
}
return conditionality1;
}
/**
* Helper function that parse healthcare entity index from the given entity reference string.
* The entity reference format is "
*
* @param entityReference the given healthcare entity reference string.
*
* @return the healthcare entity index.
*/
private static Integer getHealthcareEntityIndex(String entityReference) {
if (!CoreUtils.isNullOrEmpty(entityReference)) {
int lastIndex = entityReference.lastIndexOf('/');
if (lastIndex != -1) {
return Integer.parseInt(entityReference.substring(lastIndex + 1));
}
}
throw LOGGER.logExceptionAsError(
new RuntimeException("Failed to parse healthcare entity index from: " + entityReference));
}
/**
* Transfer {@link com.azure.ai.textanalytics.models.StringIndexType} into auto-generated {@link StringIndexType}.
* If value is null, use the default type for java, UTF16CODE_UNIT.
*
* @param stringIndexType The public explored StringIndexType.
*
* @return The autogenerated internally used StringIndexType.
*/
public static StringIndexType getNonNullStringIndexType(
com.azure.ai.textanalytics.models.StringIndexType stringIndexType) {
return stringIndexType == null ? StringIndexType.UTF16CODE_UNIT
: StringIndexType.fromString(stringIndexType.toString());
}
/**
* Get the non-null {@link Context}. The default value is {@link Context
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context getNotNullContext(Context context) {
return context == null ? Context.NONE : context;
}
/**
* Helper function which retrieves the size of an {@link Iterable}.
*
* @param documents The iterable of documents.
* @return Count of documents in the iterable.
*/
public static int getDocumentCount(Iterable<?> documents) {
if (documents instanceof Collection) {
return ((Collection<?>) documents).size();
} else {
final int[] count = new int[] { 0 };
documents.forEach(ignored -> count[0] += 1);
return count[0];
}
}
/**
* Helper function which convert the {@code Iterable<PiiEntityCategory>} to {@code List<PiiCategory>}.
*
* @param categoriesFilter the iterable of {@link PiiEntityCategory}.
* @return the list of {@link PiiCategory}.
*/
public static List<PiiCategory> toCategoriesFilter(Iterable<PiiEntityCategory> categoriesFilter) {
if (categoriesFilter == null) {
return null;
}
final List<PiiCategory> piiCategories = new ArrayList<>();
categoriesFilter.forEach(category -> piiCategories.add(PiiCategory.fromString(category.toString())));
return piiCategories;
}
/**
* Helper method to convert {@link SentimentResponse} to {@link AnalyzeSentimentResultCollection}.
*
* @param sentimentResponse The {@link SentimentResponse}.
*
* @return A {@link AnalyzeSentimentResultCollection}.
*/
public static AnalyzeSentimentResultCollection toAnalyzeSentimentResultCollection(
SentimentResponse sentimentResponse) {
final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>();
final List<DocumentSentiment> documentSentiments = sentimentResponse.getDocuments();
for (DocumentSentiment documentSentiment : documentSentiments) {
analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment, documentSentiments));
}
for (DocumentError documentError : sentimentResponse.getErrors()) {
analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(),
sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics()));
}
/**
* Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}.
*
* @param documentSentiment The {@link DocumentSentiment} returned by the service.
* @param documentSentimentList The document sentiment list returned by the service.
*
* @return The {@link AnalyzeSentimentResult} to be returned by the SDK.
*/
private static AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment,
List<DocumentSentiment> documentSentimentList) {
final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores();
final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream()
.map(sentenceSentiment -> {
final SentimentConfidenceScorePerLabel confidenceScorePerSentence =
sentenceSentiment.getConfidenceScores();
final SentenceSentimentValue sentenceSentimentValue = sentenceSentiment.getSentiment();
final SentenceSentiment sentenceSentiment1 = new SentenceSentiment(sentenceSentiment.getText(),
TextSentiment.fromString(sentenceSentimentValue == null ? null : sentenceSentimentValue.toString()),
new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(),
confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive()));
SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1,
toSentenceOpinionList(sentenceSentiment, documentSentimentList));
SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, sentenceSentiment.getOffset());
SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, sentenceSentiment.getLength());
return sentenceSentiment1;
}).collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map(
warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
final DocumentSentimentValue documentSentimentValue = documentSentiment.getSentiment();
return new AnalyzeSentimentResult(
documentSentiment.getId(),
documentSentiment.getStatistics() == null
? null : toTextDocumentStatistics(documentSentiment.getStatistics()),
null,
new com.azure.ai.textanalytics.models.DocumentSentiment(
TextSentiment.fromString(documentSentimentValue == null ? null : documentSentimentValue.toString()),
new SentimentConfidenceScores(
confidenceScorePerLabel.getNegative(),
confidenceScorePerLabel.getNeutral(),
confidenceScorePerLabel.getPositive()),
new IterableStream<>(sentenceSentiments),
new IterableStream<>(warnings)));
}
/*
* Transform SentenceSentiment's opinion mining to output that user can use.
*/
private static IterableStream<SentenceOpinion> toSentenceOpinionList(
com.azure.ai.textanalytics.implementation.models.SentenceSentiment sentenceSentiment,
List<DocumentSentiment> documentSentimentList) {
final List<SentenceTarget> sentenceTargets = sentenceSentiment.getTargets();
if (sentenceTargets == null) {
return null;
}
final List<SentenceOpinion> sentenceOpinions = new ArrayList<>();
sentenceTargets.forEach(sentenceTarget -> {
final List<AssessmentSentiment> assessmentSentiments = new ArrayList<>();
sentenceTarget.getRelations().forEach(targetRelation -> {
final TargetRelationType targetRelationType = targetRelation.getRelationType();
final String opinionPointer = targetRelation.getRef();
if (TargetRelationType.ASSESSMENT == targetRelationType) {
assessmentSentiments.add(toAssessmentSentiment(
findSentimentAssessment(opinionPointer, documentSentimentList)));
}
});
final TargetSentiment targetSentiment = new TargetSentiment();
TargetSentimentPropertiesHelper.setText(targetSentiment, sentenceTarget.getText());
TargetSentimentPropertiesHelper.setSentiment(targetSentiment,
TextSentiment.fromString(sentenceTarget.getSentiment().toString()));
TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment,
toSentimentConfidenceScores(sentenceTarget.getConfidenceScores()));
TargetSentimentPropertiesHelper.setOffset(targetSentiment, sentenceTarget.getOffset());
TargetSentimentPropertiesHelper.setLength(targetSentiment, sentenceTarget.getLength());
final SentenceOpinion sentenceOpinion = new SentenceOpinion();
SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion, targetSentiment);
SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion, new IterableStream<>(assessmentSentiments));
sentenceOpinions.add(sentenceOpinion);
});
return new IterableStream<>(sentenceOpinions);
}
/*
* Transform type TargetConfidenceScoreLabel to SentimentConfidenceScores.
*/
private static SentimentConfidenceScores toSentimentConfidenceScores(
TargetConfidenceScoreLabel targetConfidenceScoreLabel) {
return new SentimentConfidenceScores(targetConfidenceScoreLabel.getNegative(), NEUTRAL_SCORE_ZERO,
targetConfidenceScoreLabel.getPositive());
}
/*
* Transform type SentenceOpinion to OpinionSentiment.
*/
private static AssessmentSentiment toAssessmentSentiment(SentenceAssessment sentenceAssessment) {
final AssessmentSentiment assessmentSentiment = new AssessmentSentiment();
AssessmentSentimentPropertiesHelper.setText(assessmentSentiment, sentenceAssessment.getText());
AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment,
TextSentiment.fromString(sentenceAssessment.getSentiment().toString()));
AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment,
toSentimentConfidenceScores(sentenceAssessment.getConfidenceScores()));
AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment, sentenceAssessment.isNegated());
AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment, sentenceAssessment.getOffset());
AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment, sentenceAssessment.getLength());
return assessmentSentiment;
}
/*
* Parses the reference pointer to an index array that contains document, sentence, and opinion indexes.
*/
/*
* Find the specific sentence assessment in the document sentiment list by given the assessment reference pointer.
*/
public static SentenceAssessment findSentimentAssessment(String assessmentPointer,
List<DocumentSentiment> documentSentiments) {
final int[] assessmentIndexes = parseRefPointerToIndexArray(assessmentPointer);
final int documentIndex = assessmentIndexes[0];
final int sentenceIndex = assessmentIndexes[1];
final int assessmentIndex = assessmentIndexes[2];
if (documentIndex >= documentSentiments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid document index '%s' in '%s'.", documentIndex, assessmentPointer)));
}
final DocumentSentiment documentsentiment = documentSentiments.get(documentIndex);
final List<com.azure.ai.textanalytics.implementation.models.SentenceSentiment> sentenceSentiments =
documentsentiment.getSentences();
if (sentenceIndex >= sentenceSentiments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid sentence index '%s' in '%s'.", sentenceIndex, assessmentPointer)));
}
final List<SentenceAssessment> assessments = sentenceSentiments.get(sentenceIndex).getAssessments();
if (assessmentIndex >= assessments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid assessment index '%s' in '%s'.", assessmentIndex, assessmentPointer)));
}
return assessments.get(assessmentIndex);
}
} | class Utility {
public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(5);
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private static final int NEUTRAL_SCORE_ZERO = 0;
private static final String DOCUMENT_SENTENCES_ASSESSMENTS_REG_EXP =
"
private static final Pattern PATTERN;
static {
PATTERN = Pattern.compile(DOCUMENT_SENTENCES_ASSESSMENTS_REG_EXP);
}
private Utility() {
}
/**
* Verify that list of documents are not null or empty. Otherwise, throw exception.
*
* @param documents A list of documents.
*
* @throws NullPointerException if {@code documents} is null.
* @throws IllegalArgumentException if {@code documents} is empty.
*/
public static void inputDocumentsValidation(Iterable<?> documents) {
Objects.requireNonNull(documents, "'documents' cannot be null.");
final Iterator<?> iterator = documents.iterator();
if (!iterator.hasNext()) {
throw new IllegalArgumentException("'documents' cannot be empty.");
}
}
/**
* Mapping a {@link ErrorResponseException} to {@link HttpResponseException} if exist. Otherwise, return
* original {@link Throwable}.
*
* @param throwable A {@link Throwable}.
* @return A {@link HttpResponseException} or the original throwable type.
*/
public static Throwable mapToHttpResponseExceptionIfExists(Throwable throwable) {
if (throwable instanceof ErrorResponseException) {
ErrorResponseException errorException = (ErrorResponseException) throwable;
final ErrorResponse errorResponse = errorException.getValue();
com.azure.ai.textanalytics.models.TextAnalyticsError textAnalyticsError = null;
if (errorResponse != null && errorResponse.getError() != null) {
textAnalyticsError = toTextAnalyticsError(errorResponse.getError());
}
return new HttpResponseException(errorException.getMessage(), errorException.getResponse(),
textAnalyticsError);
}
return throwable;
}
/**
* Given a list of documents will apply the indexing function to it and return the updated list.
*
* @param documents the inputs to apply the mapping function to.
* @param mappingFunction the function which applies the index to the incoming input value.
* @param <T> the type of items being returned in the list.
* @return The list holding all the generic items combined.
*/
public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) {
Objects.requireNonNull(documents, "'documents' cannot be null.");
AtomicInteger i = new AtomicInteger(0);
List<T> result = new ArrayList<>();
documents.forEach(document ->
result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document))
);
return result;
}
/**
* Convert {@link DocumentStatistics} to {@link TextDocumentStatistics}
*
* @param statistics the {@link DocumentStatistics} provided by the service.
* @return the {@link TextDocumentStatistics} returned by the SDK.
*/
public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) {
return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount());
}
/**
* Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics}
*
* @param statistics the {@link RequestStatistics} provided by the service.
* @return the {@link TextDocumentBatchStatistics} returned by the SDK.
*/
public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) {
return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(),
statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount());
}
/**
* Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError}
* This function maps the service returned {@link TextAnalyticsError inner error} to the top level
* {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present.
*
* @param textAnalyticsError the {@link TextAnalyticsError} returned by the service.
* @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK.
*/
public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError(
TextAnalyticsError textAnalyticsError) {
final InnerError innerError = textAnalyticsError.getInnererror();
if (innerError == null) {
final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode();
return new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()),
textAnalyticsError.getMessage(),
textAnalyticsError.getTarget());
}
final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode();
return new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()),
innerError.getMessage(),
innerError.getTarget());
}
/**
* Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}.
*
* @param documents the user provided input in {@link TextDocumentInput}
* @return the service required input {@link MultiLanguageInput}
*/
public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) {
List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>();
for (TextDocumentInput textDocumentInput : documents) {
multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId())
.setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage()));
}
return multiLanguageInputs;
}
/**
* Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError}
* to a {@link TextAnalyticsException}.
*
* @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}.
* @return the {@link TextAnalyticsException} to be thrown.
*/
public static TextAnalyticsException toTextAnalyticsException(
com.azure.ai.textanalytics.models.TextAnalyticsError error) {
return new TextAnalyticsException(error.getMessage(), error.getErrorCode(), error.getTarget());
}
/**
* Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}.
*
* @param documents The list of documents to detect languages for.
*
* @return a list of {@link LanguageInput}.
*/
public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) {
final List<LanguageInput> multiLanguageInputs = new ArrayList<>();
documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput()
.setId(textDocumentInput.getId())
.setText(textDocumentInput.getText())
.setCountryHint(textDocumentInput.getCountryHint())));
return multiLanguageInputs;
}
/**
* Extracts the operation ID from the 'operation-location' URL. An example of 'operation-location' is
* https:
*
* @param operationLocation The URL specified in the 'Operation-Location' response header containing the
* operation ID used to track the progress and obtain the ID of the analyze operation.
*
* @return The operation ID that tracks the long running operation progress.
*/
public static String parseOperationId(String operationLocation) {
if (!CoreUtils.isNullOrEmpty(operationLocation)) {
int lastIndex = operationLocation.lastIndexOf('/');
if (lastIndex != -1) {
return operationLocation.substring(lastIndex + 1);
}
}
throw LOGGER.logExceptionAsError(
new RuntimeException("Failed to parse operation header for operation Id from: " + operationLocation));
}
/**
* Extract the next pagination link which contains the request parameter values, into map,
* such as '$skip=20' and '$top=2'.
*
* @param nextLink the next pagination link.
*
* @return A map that holds the request parameter value of next pagination link.
*/
public static Map<String, Object> parseNextLink(String nextLink) {
if (!CoreUtils.isNullOrEmpty(nextLink)) {
final Map<String, Object> parameterMap = new HashMap<>();
final String[] strings = nextLink.split("\\?", 2);
final String[] parameters = strings[1].split("&");
for (String parameter : parameters) {
final String[] parameterPair = parameter.split("=");
final String key = parameterPair[0];
final String value = parameterPair[1];
if ("showStats".equals(key)) {
parameterMap.put(key, value);
} else if ("$skip".equals(key) || "$top".equals(key)) {
parameterMap.put(key, Integer.valueOf(value));
}
}
return parameterMap;
}
return new HashMap<>();
}
public static RecognizeEntitiesResultCollection toRecognizeEntitiesResultCollectionResponse(
final EntitiesResult entitiesResult) {
List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
entitiesResult.getDocuments().forEach(documentEntities ->
recognizeEntitiesResults.add(new RecognizeEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new CategorizedEntityCollection(
new IterableStream<>(documentEntities.getEntities().stream().map(entity -> {
final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(),
EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(),
entity.getConfidenceScore(), entity.getOffset());
CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength());
return categorizedEntity;
}).collect(Collectors.toList())),
new IterableStream<>(documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())))
)));
for (DocumentError documentError : entitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, entitiesResult.getModelVersion(),
entitiesResult.getStatistics() == null ? null : toBatchStatistics(entitiesResult.getStatistics()));
}
public static RecognizePiiEntitiesResultCollection toRecognizePiiEntitiesResultCollection(
final PiiResult piiEntitiesResult) {
final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
piiEntitiesResult.getDocuments().forEach(documentEntities -> {
final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity -> {
final PiiEntity piiEntity = new PiiEntity();
PiiEntityPropertiesHelper.setText(piiEntity, entity.getText());
PiiEntityPropertiesHelper.setCategory(piiEntity, PiiEntityCategory.fromString(entity.getCategory()));
PiiEntityPropertiesHelper.setSubcategory(piiEntity, entity.getSubcategory());
PiiEntityPropertiesHelper.setConfidenceScore(piiEntity, entity.getConfidenceScore());
PiiEntityPropertiesHelper.setOffset(piiEntity, entity.getOffset());
return piiEntity;
}).collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(),
new IterableStream<>(warnings))
));
});
for (DocumentError documentError : piiEntitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(),
piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics()));
}
public static ExtractKeyPhrasesResultCollection toExtractKeyPhrasesResultCollection(
final KeyPhraseResult keyPhraseResult) {
final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>();
for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) {
final String documentId = documentKeyPhrases.getId();
keyPhraseResultList.add(new ExtractKeyPhraseResult(
documentId,
documentKeyPhrases.getStatistics() == null ? null
: toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null,
new KeyPhrasesCollection(
new IterableStream<>(documentKeyPhrases.getKeyPhrases()),
new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())))));
}
for (DocumentError documentError : keyPhraseResult.getErrors()) {
keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(),
keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()));
}
public static Response<RecognizeLinkedEntitiesResultCollection> toRecognizeLinkedEntitiesResultCollectionResponse(
final Response<EntityLinkingResult> response) {
final EntityLinkingResult entityLinkingResult = response.getValue();
return new SimpleResponse<>(response,
new RecognizeLinkedEntitiesResultCollection(toRecognizeLinkedEntitiesResultCollection(entityLinkingResult),
entityLinkingResult.getModelVersion(),
entityLinkingResult.getStatistics() == null ? null
: toBatchStatistics(entityLinkingResult.getStatistics())));
}
public static RecognizeLinkedEntitiesResultCollection toRecognizeLinkedEntitiesResultCollection(
final EntityLinkingResult entityLinkingResult) {
final List<RecognizeLinkedEntitiesResult> linkedEntitiesResults =
entityLinkingResult.getDocuments().stream().map(
documentLinkedEntities -> new RecognizeLinkedEntitiesResult(
documentLinkedEntities.getId(),
documentLinkedEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentLinkedEntities.getStatistics()),
null,
new LinkedEntityCollection(new IterableStream<>(
documentLinkedEntities.getEntities().stream().map(
linkedEntity -> new LinkedEntity(
linkedEntity.getName(),
new IterableStream<>(
linkedEntity.getMatches().stream().map(
match -> {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch(
match.getText(), match.getConfidenceScore(), match.getOffset());
LinkedEntityMatchPropertiesHelper.setLength(linkedEntityMatch,
match.getLength());
return linkedEntityMatch;
}).collect(Collectors.toList())),
linkedEntity.getLanguage(),
linkedEntity.getId(),
linkedEntity.getUrl(),
linkedEntity.getDataSource(),
linkedEntity.getBingId())).collect(Collectors.toList())),
new IterableStream<>(documentLinkedEntities.getWarnings().stream().map(
warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null
: warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList())
)
)
)
).collect(Collectors.toList());
for (DocumentError documentError : entityLinkingResult.getErrors()) {
linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new RecognizeLinkedEntitiesResultCollection(linkedEntitiesResults, entityLinkingResult.getModelVersion(),
entityLinkingResult.getStatistics() == null ? null
: toBatchStatistics(entityLinkingResult.getStatistics()));
}
/**
* Transfer {@link HealthcareResult} into {@link IterableStream} of {@link AnalyzeHealthcareEntitiesResult}.
*
* @param healthcareResult the service side raw data, HealthcareResult.
*
* @return the client side explored model, RecognizeHealthcareEntitiesResultCollection.
*/
public static IterableStream<AnalyzeHealthcareEntitiesResult> toRecognizeHealthcareEntitiesResults(
HealthcareResult healthcareResult) {
List<AnalyzeHealthcareEntitiesResult> analyzeHealthcareEntitiesResults = new ArrayList<>();
healthcareResult.getDocuments().forEach(
documentEntities -> {
final AnalyzeHealthcareEntitiesResult analyzeHealthcareEntitiesResult =
new AnalyzeHealthcareEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null);
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map(
textAnalyticsWarning -> new TextAnalyticsWarning(
Optional.ofNullable(textAnalyticsWarning.getCode())
.map(warningCodeValue -> WarningCode.fromString(warningCodeValue.toString()))
.orElse(null),
textAnalyticsWarning.getMessage())
).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setWarnings(analyzeHealthcareEntitiesResult,
IterableStream.of(warnings));
final List<HealthcareEntity> healthcareEntities = documentEntities.getEntities().stream().map(
entity -> {
final HealthcareEntity healthcareEntity = new HealthcareEntity();
HealthcareEntityPropertiesHelper.setText(healthcareEntity, entity.getText());
HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity, entity.getName());
HealthcareEntityPropertiesHelper.setCategory(healthcareEntity, entity.getCategory());
HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity,
entity.getConfidenceScore());
HealthcareEntityPropertiesHelper.setOffset(healthcareEntity, entity.getOffset());
HealthcareEntityPropertiesHelper.setLength(healthcareEntity, entity.getLength());
final List<EntityDataSource> entityDataSources =
Optional.ofNullable(entity.getLinks()).map(
links -> links.stream().map(
link -> {
final EntityDataSource dataSource = new EntityDataSource();
EntityDataSourcePropertiesHelper.setName(dataSource, link.getDataSource());
EntityDataSourcePropertiesHelper.setEntityId(dataSource, link.getId());
return dataSource;
}
).collect(Collectors.toList()))
.orElse(new ArrayList<>());
HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity,
IterableStream.of(entityDataSources));
final HealthcareAssertion assertion = entity.getAssertion();
if (assertion != null) {
HealthcareEntityPropertiesHelper.setAssertion(healthcareEntity,
toHealthcareEntityAssertion(assertion));
}
return healthcareEntity;
}).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(analyzeHealthcareEntitiesResult,
IterableStream.of(healthcareEntities));
final List<HealthcareEntityRelation> healthcareEntityRelations =
documentEntities.getRelations().stream().map(
healthcareRelation -> {
final HealthcareEntityRelation entityRelation = new HealthcareEntityRelation();
final RelationType relationType = healthcareRelation.getRelationType();
if (relationType != null) {
HealthcareEntityRelationPropertiesHelper.setRelationType(entityRelation,
HealthcareEntityRelationType.fromString(relationType.toString()));
}
final List<HealthcareEntityRelationRole> relationRoles =
healthcareRelation.getEntities().stream().map(
relationEntity -> {
final HealthcareEntityRelationRole relationRole =
new HealthcareEntityRelationRole();
HealthcareEntityRelationRolePropertiesHelper.setName(relationRole,
relationEntity.getRole());
HealthcareEntityRelationRolePropertiesHelper.setEntity(relationRole,
healthcareEntities.get(getHealthcareEntityIndex(relationEntity.getRef())));
return relationRole;
}).collect(Collectors.toList());
HealthcareEntityRelationPropertiesHelper.setRoles(entityRelation,
IterableStream.of(relationRoles));
return entityRelation;
}).collect(Collectors.toList());
AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(analyzeHealthcareEntitiesResult,
IterableStream.of(healthcareEntityRelations));
analyzeHealthcareEntitiesResults.add(analyzeHealthcareEntitiesResult);
});
healthcareResult.getErrors().forEach(documentError ->
analyzeHealthcareEntitiesResults.add(new AnalyzeHealthcareEntitiesResult(
documentError.getId(),
null,
toTextAnalyticsError(documentError.getError())))
);
return IterableStream.of(analyzeHealthcareEntitiesResults);
}
public static HealthcareEntityAssertion toHealthcareEntityAssertion(HealthcareAssertion healthcareAssertion) {
final Association association = healthcareAssertion.getAssociation();
final Certainty certainty = healthcareAssertion.getCertainty();
final Conditionality conditionality = healthcareAssertion.getConditionality();
final HealthcareEntityAssertion entityAssertion = new HealthcareEntityAssertion();
if (association != null) {
HealthcareEntityAssertionPropertiesHelper.setAssociation(entityAssertion,
EntityAssociation.fromString(association.toString()));
}
if (certainty != null) {
HealthcareEntityAssertionPropertiesHelper.setCertainty(entityAssertion,
toCertainty(certainty));
}
if (conditionality != null) {
HealthcareEntityAssertionPropertiesHelper.setConditionality(entityAssertion,
toConditionality(conditionality));
}
return entityAssertion;
}
private static EntityCertainty toCertainty(Certainty certainty) {
EntityCertainty entityCertainty1 = null;
switch (certainty) {
case POSITIVE:
entityCertainty1 = EntityCertainty.POSITIVE;
break;
case POSITIVE_POSSIBLE:
entityCertainty1 = EntityCertainty.POSITIVE_POSSIBLE;
break;
case NEUTRAL_POSSIBLE:
entityCertainty1 = EntityCertainty.NEUTRAL_POSSIBLE;
break;
case NEGATIVE_POSSIBLE:
entityCertainty1 = EntityCertainty.NEGATIVE_POSSIBLE;
break;
case NEGATIVE:
entityCertainty1 = EntityCertainty.NEGATIVE;
break;
default:
break;
}
return entityCertainty1;
}
private static EntityConditionality toConditionality(Conditionality conditionality) {
EntityConditionality conditionality1 = null;
switch (conditionality) {
case HYPOTHETICAL:
conditionality1 = EntityConditionality.HYPOTHETICAL;
break;
case CONDITIONAL:
conditionality1 = EntityConditionality.CONDITIONAL;
break;
default:
break;
}
return conditionality1;
}
/**
* Helper function that parse healthcare entity index from the given entity reference string.
* The entity reference format is "
*
* @param entityReference the given healthcare entity reference string.
*
* @return the healthcare entity index.
*/
private static Integer getHealthcareEntityIndex(String entityReference) {
if (!CoreUtils.isNullOrEmpty(entityReference)) {
int lastIndex = entityReference.lastIndexOf('/');
if (lastIndex != -1) {
return Integer.parseInt(entityReference.substring(lastIndex + 1));
}
}
throw LOGGER.logExceptionAsError(
new RuntimeException("Failed to parse healthcare entity index from: " + entityReference));
}
/**
* Transfer {@link com.azure.ai.textanalytics.models.StringIndexType} into auto-generated {@link StringIndexType}.
* If value is null, use the default type for java, UTF16CODE_UNIT.
*
* @param stringIndexType The public explored StringIndexType.
*
* @return The autogenerated internally used StringIndexType.
*/
public static StringIndexType getNonNullStringIndexType(
com.azure.ai.textanalytics.models.StringIndexType stringIndexType) {
return stringIndexType == null ? StringIndexType.UTF16CODE_UNIT
: StringIndexType.fromString(stringIndexType.toString());
}
/**
* Get the non-null {@link Context}. The default value is {@link Context
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context getNotNullContext(Context context) {
return context == null ? Context.NONE : context;
}
/**
* Helper function which retrieves the size of an {@link Iterable}.
*
* @param documents The iterable of documents.
* @return Count of documents in the iterable.
*/
public static int getDocumentCount(Iterable<?> documents) {
if (documents instanceof Collection) {
return ((Collection<?>) documents).size();
} else {
final int[] count = new int[] { 0 };
documents.forEach(ignored -> count[0] += 1);
return count[0];
}
}
/**
* Helper function which convert the {@code Iterable<PiiEntityCategory>} to {@code List<PiiCategory>}.
*
* @param categoriesFilter the iterable of {@link PiiEntityCategory}.
* @return the list of {@link PiiCategory}.
*/
public static List<PiiCategory> toCategoriesFilter(Iterable<PiiEntityCategory> categoriesFilter) {
if (categoriesFilter == null) {
return null;
}
final List<PiiCategory> piiCategories = new ArrayList<>();
categoriesFilter.forEach(category -> piiCategories.add(PiiCategory.fromString(category.toString())));
return piiCategories;
}
/**
* Helper method to convert {@link SentimentResponse} to {@link AnalyzeSentimentResultCollection}.
*
* @param sentimentResponse The {@link SentimentResponse}.
*
* @return A {@link AnalyzeSentimentResultCollection}.
*/
public static AnalyzeSentimentResultCollection toAnalyzeSentimentResultCollection(
SentimentResponse sentimentResponse) {
final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>();
final List<DocumentSentiment> documentSentiments = sentimentResponse.getDocuments();
for (DocumentSentiment documentSentiment : documentSentiments) {
analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment, documentSentiments));
}
for (DocumentError documentError : sentimentResponse.getErrors()) {
analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(),
sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics()));
}
/**
* Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}.
*
* @param documentSentiment The {@link DocumentSentiment} returned by the service.
* @param documentSentimentList The document sentiment list returned by the service.
*
* @return The {@link AnalyzeSentimentResult} to be returned by the SDK.
*/
private static AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment,
List<DocumentSentiment> documentSentimentList) {
final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores();
final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream()
.map(sentenceSentiment -> {
final SentimentConfidenceScorePerLabel confidenceScorePerSentence =
sentenceSentiment.getConfidenceScores();
final SentenceSentimentValue sentenceSentimentValue = sentenceSentiment.getSentiment();
final SentenceSentiment sentenceSentiment1 = new SentenceSentiment(sentenceSentiment.getText(),
TextSentiment.fromString(sentenceSentimentValue == null ? null : sentenceSentimentValue.toString()),
new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(),
confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive()));
SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1,
toSentenceOpinionList(sentenceSentiment, documentSentimentList));
SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, sentenceSentiment.getOffset());
SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, sentenceSentiment.getLength());
return sentenceSentiment1;
}).collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map(
warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
final DocumentSentimentValue documentSentimentValue = documentSentiment.getSentiment();
return new AnalyzeSentimentResult(
documentSentiment.getId(),
documentSentiment.getStatistics() == null
? null : toTextDocumentStatistics(documentSentiment.getStatistics()),
null,
new com.azure.ai.textanalytics.models.DocumentSentiment(
TextSentiment.fromString(documentSentimentValue == null ? null : documentSentimentValue.toString()),
new SentimentConfidenceScores(
confidenceScorePerLabel.getNegative(),
confidenceScorePerLabel.getNeutral(),
confidenceScorePerLabel.getPositive()),
new IterableStream<>(sentenceSentiments),
new IterableStream<>(warnings)));
}
/*
* Transform SentenceSentiment's opinion mining to output that user can use.
*/
private static IterableStream<SentenceOpinion> toSentenceOpinionList(
com.azure.ai.textanalytics.implementation.models.SentenceSentiment sentenceSentiment,
List<DocumentSentiment> documentSentimentList) {
final List<SentenceTarget> sentenceTargets = sentenceSentiment.getTargets();
if (sentenceTargets == null) {
return null;
}
final List<SentenceOpinion> sentenceOpinions = new ArrayList<>();
sentenceTargets.forEach(sentenceTarget -> {
final List<AssessmentSentiment> assessmentSentiments = new ArrayList<>();
sentenceTarget.getRelations().forEach(targetRelation -> {
final TargetRelationType targetRelationType = targetRelation.getRelationType();
final String opinionPointer = targetRelation.getRef();
if (TargetRelationType.ASSESSMENT == targetRelationType) {
assessmentSentiments.add(toAssessmentSentiment(
findSentimentAssessment(opinionPointer, documentSentimentList)));
}
});
final TargetSentiment targetSentiment = new TargetSentiment();
TargetSentimentPropertiesHelper.setText(targetSentiment, sentenceTarget.getText());
TargetSentimentPropertiesHelper.setSentiment(targetSentiment,
TextSentiment.fromString(sentenceTarget.getSentiment().toString()));
TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment,
toSentimentConfidenceScores(sentenceTarget.getConfidenceScores()));
TargetSentimentPropertiesHelper.setOffset(targetSentiment, sentenceTarget.getOffset());
TargetSentimentPropertiesHelper.setLength(targetSentiment, sentenceTarget.getLength());
final SentenceOpinion sentenceOpinion = new SentenceOpinion();
SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion, targetSentiment);
SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion, new IterableStream<>(assessmentSentiments));
sentenceOpinions.add(sentenceOpinion);
});
return new IterableStream<>(sentenceOpinions);
}
/*
* Transform type TargetConfidenceScoreLabel to SentimentConfidenceScores.
*/
private static SentimentConfidenceScores toSentimentConfidenceScores(
TargetConfidenceScoreLabel targetConfidenceScoreLabel) {
return new SentimentConfidenceScores(targetConfidenceScoreLabel.getNegative(), NEUTRAL_SCORE_ZERO,
targetConfidenceScoreLabel.getPositive());
}
/*
* Transform type SentenceOpinion to OpinionSentiment.
*/
private static AssessmentSentiment toAssessmentSentiment(SentenceAssessment sentenceAssessment) {
final AssessmentSentiment assessmentSentiment = new AssessmentSentiment();
AssessmentSentimentPropertiesHelper.setText(assessmentSentiment, sentenceAssessment.getText());
AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment,
TextSentiment.fromString(sentenceAssessment.getSentiment().toString()));
AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment,
toSentimentConfidenceScores(sentenceAssessment.getConfidenceScores()));
AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment, sentenceAssessment.isNegated());
AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment, sentenceAssessment.getOffset());
AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment, sentenceAssessment.getLength());
return assessmentSentiment;
}
/*
* Parses the reference pointer to an index array that contains document, sentence, and opinion indexes.
*/
/*
* Find the specific sentence assessment in the document sentiment list by given the assessment reference pointer.
*/
public static SentenceAssessment findSentimentAssessment(String assessmentPointer,
List<DocumentSentiment> documentSentiments) {
final int[] assessmentIndexes = parseRefPointerToIndexArray(assessmentPointer);
final int documentIndex = assessmentIndexes[0];
final int sentenceIndex = assessmentIndexes[1];
final int assessmentIndex = assessmentIndexes[2];
if (documentIndex >= documentSentiments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid document index '%s' in '%s'.", documentIndex, assessmentPointer)));
}
final DocumentSentiment documentsentiment = documentSentiments.get(documentIndex);
final List<com.azure.ai.textanalytics.implementation.models.SentenceSentiment> sentenceSentiments =
documentsentiment.getSentences();
if (sentenceIndex >= sentenceSentiments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid sentence index '%s' in '%s'.", sentenceIndex, assessmentPointer)));
}
final List<SentenceAssessment> assessments = sentenceSentiments.get(sentenceIndex).getAssessments();
if (assessmentIndex >= assessments.size()) {
throw LOGGER.logExceptionAsError(new IllegalStateException(
String.format("Invalid assessment index '%s' in '%s'.", assessmentIndex, assessmentPointer)));
}
return assessments.get(assessmentIndex);
}
} |
out of curiosity, do you know when will this be fixed? | private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) {
return new JobManifestTasks()
.setEntityRecognitionTasks(actions.getRecognizeEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntitiesTask entitiesTask = new EntitiesTask();
entitiesTask.setParameters(
new EntitiesTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType())));
return entitiesTask;
}).collect(Collectors.toList()))
.setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizePiiEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final PiiTask piiTask = new PiiTask();
piiTask.setParameters(
new PiiTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
.setDomain(PiiTaskParametersDomain.fromString(
action.getDomainFilter() == null ? null
: action.getDomainFilter().toString()))
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType()))
.setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))
);
return piiTask;
}).collect(Collectors.toList()))
.setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesOptions() == null ? null
: StreamSupport.stream(actions.getExtractKeyPhrasesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask();
keyPhrasesTask.setParameters(
new KeyPhrasesTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
);
return keyPhrasesTask;
}).collect(Collectors.toList()))
.setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeLinkedEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntityLinkingTask entityLinkingTask = new EntityLinkingTask();
entityLinkingTask.setParameters(
new EntityLinkingTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
);
return entityLinkingTask;
}).collect(Collectors.toList()))
.setSentimentAnalysisTasks(actions.getAnalyzeSentimentOptions() == null ? null
: StreamSupport.stream(actions.getAnalyzeSentimentOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask();
sentimentAnalysisTask.setParameters(
new SentimentAnalysisTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
);
return sentimentAnalysisTask;
}).collect(Collectors.toList()));
} | new SentimentAnalysisTaskParameters() | private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) {
return new JobManifestTasks()
.setEntityRecognitionTasks(actions.getRecognizeEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntitiesTask entitiesTask = new EntitiesTask();
entitiesTask.setParameters(
new EntitiesTaskParameters()
.setModelVersion(action.getModelVersion())
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType())));
return entitiesTask;
}).collect(Collectors.toList()))
.setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizePiiEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final PiiTask piiTask = new PiiTask();
piiTask.setParameters(
new PiiTaskParameters()
.setModelVersion(action.getModelVersion())
.setDomain(PiiTaskParametersDomain.fromString(
action.getDomainFilter() == null ? null
: action.getDomainFilter().toString()))
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType()))
.setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))
);
return piiTask;
}).collect(Collectors.toList()))
.setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesOptions() == null ? null
: StreamSupport.stream(actions.getExtractKeyPhrasesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask();
keyPhrasesTask.setParameters(
new KeyPhrasesTaskParameters()
.setModelVersion(action.getModelVersion())
);
return keyPhrasesTask;
}).collect(Collectors.toList()))
.setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeLinkedEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntityLinkingTask entityLinkingTask = new EntityLinkingTask();
entityLinkingTask.setParameters(
new EntityLinkingTaskParameters()
.setModelVersion(action.getModelVersion())
);
return entityLinkingTask;
}).collect(Collectors.toList()))
.setSentimentAnalysisTasks(actions.getAnalyzeSentimentOptions() == null ? null
: StreamSupport.stream(actions.getAnalyzeSentimentOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask();
sentimentAnalysisTask.setParameters(
new SentimentAnalysisTaskParameters()
.setModelVersion(action.getModelVersion())
);
return sentimentAnalysisTask;
}).collect(Collectors.toList()));
} | class AnalyzeActionsAsyncClient {
private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks";
private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks";
private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks";
private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks";
private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks";
private static final String REGEX_ACTION_ERROR_TARGET = "
+ "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)";
private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class);
private final TextAnalyticsClientImpl service;
AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
PollerFlux<AnalyzeActionsOperationDetail, PagedFlux<AnalyzeActionsResult>> beginAnalyzeActions(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail textAnalyticsOperationResult =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper
.setOperationId(textAnalyticsOperationResult,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return textAnalyticsOperationResult;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext)))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
PollerFlux<AnalyzeActionsOperationDetail, PagedIterable<AnalyzeActionsResult>> beginAnalyzeActionsIterable(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail operationDetail =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return operationDetail;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperationIterable(operationId -> Mono.just(new PagedIterable<>(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext))))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>>
activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) {
return pollingContext -> {
try {
return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>>
pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) {
return pollingContext -> {
try {
final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse =
pollingContext.getLatestResponse();
final String operationId = operationResultPollResponse.getValue().getOperationId();
return pollingFunction.apply(operationId)
.flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse))
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PagedFlux<AnalyzeActionsResult>>>
fetchingOperation(Function<String, Mono<PagedFlux<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PagedIterable<AnalyzeActionsResult>>>
fetchingOperationIterable(Function<String, Mono<PagedIterable<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
PagedFlux<AnalyzeActionsResult> getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip,
boolean showStats, Context context) {
return new PagedFlux<>(
() -> getPage(null, operationId, top, skip, showStats, context),
continuationToken -> getPage(continuationToken, operationId, top, skip, showStats, context));
}
Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top,
Integer skip, boolean showStats, Context context) {
if (continuationToken != null) {
final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken);
final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null);
final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null);
final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false);
return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} else {
return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
}
}
private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) {
final AnalyzeJobState analyzeJobState = response.getValue();
return new PagedResponseBase<Void, AnalyzeActionsResult>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
Arrays.asList(toAnalyzeActionsResult(analyzeJobState)),
analyzeJobState.getNextLink(),
null);
}
private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) {
TasksStateTasks tasksStateTasks = analyzeJobState.getTasks();
final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems =
tasksStateTasks.getEntityRecognitionPiiTasks();
final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems =
tasksStateTasks.getEntityRecognitionTasks();
final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks =
tasksStateTasks.getKeyPhraseExtractionTasks();
final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems =
tasksStateTasks.getEntityLinkingTasks();
final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems =
tasksStateTasks.getSentimentAnalysisTasks();
List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>();
List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>();
List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>();
List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>();
List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>();
if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) {
for (int i = 0; i < entityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i);
final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult();
final EntitiesResult results = taskItem.getResults();
if (results != null) {
RecognizeEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizeEntitiesResultCollectionResponse(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(piiTasksItems)) {
for (int i = 0; i < piiTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i);
final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult();
final PiiResult results = taskItem.getResults();
if (results != null) {
RecognizePiiEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizePiiEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizePiiEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) {
for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) {
final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i);
final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult();
final KeyPhraseResult results = taskItem.getResults();
if (results != null) {
ExtractKeyPhrasesActionResultPropertiesHelper.setResult(actionResult,
toExtractKeyPhrasesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
extractKeyPhrasesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) {
for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i);
final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult();
final EntityLinkingResult results = taskItem.getResults();
if (results != null) {
RecognizeLinkedEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizeLinkedEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeLinkedEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) {
for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) {
final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i);
final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult();
final SentimentResponse results = taskItem.getResults();
if (results != null) {
AnalyzeSentimentActionResultPropertiesHelper.setResult(actionResult,
toAnalyzeSentimentResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
analyzeSentimentActionResults.add(actionResult);
}
}
final List<TextAnalyticsError> errors = analyzeJobState.getErrors();
if (!CoreUtils.isNullOrEmpty(errors)) {
for (TextAnalyticsError error : errors) {
final String[] targetPair = parseActionErrorTarget(error.getTarget());
final String taskName = targetPair[0];
final Integer taskIndex = Integer.valueOf(targetPair[1]);
final TextAnalyticsActionResult actionResult;
if (ENTITY_RECOGNITION_TASKS.equals(taskName)) {
actionResult = recognizeEntitiesActionResults.get(taskIndex);
} else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) {
actionResult = recognizePiiEntitiesActionResults.get(taskIndex);
} else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) {
actionResult = extractKeyPhrasesActionResults.get(taskIndex);
} else if (ENTITY_LINKING_TASKS.equals(taskName)) {
actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex);
} else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) {
actionResult = analyzeSentimentActionResults.get(taskIndex);
} else {
throw logger.logExceptionAsError(new RuntimeException(
"Invalid task name in target reference, " + taskName));
}
TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true);
TextAnalyticsActionResultPropertiesHelper.setError(actionResult,
new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(
error.getCode() == null ? null : error.getCode().toString()),
error.getMessage(), null));
}
}
final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult();
final RequestStatistics requestStatistics = analyzeJobState.getStatistics();
TextDocumentBatchStatistics batchStatistics = null;
if (requestStatistics != null) {
batchStatistics = new TextDocumentBatchStatistics(
requestStatistics.getDocumentsCount(), requestStatistics.getErroneousDocumentsCount(),
requestStatistics.getValidDocumentsCount(), requestStatistics.getTransactionsCount()
);
}
AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, batchStatistics);
AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizePiiEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult,
IterableStream.of(extractKeyPhrasesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeLinkedEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult,
IterableStream.of(analyzeSentimentActionResults));
return analyzeActionsResult;
}
private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse(
Response<AnalyzeJobState> analyzeJobStateResponse,
PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) {
LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) {
switch (analyzeJobStateResponse.getValue().getStatus()) {
case NOT_STARTED:
case RUNNING:
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case SUCCEEDED:
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case CANCELLED:
status = LongRunningOperationStatus.USER_CANCELLED;
break;
default:
status = LongRunningOperationStatus.fromString(
analyzeJobStateResponse.getValue().getStatus().toString(), true);
break;
}
}
AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getDisplayName());
AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getCreatedDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getExpirationDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getLastUpdateDateTime());
final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks();
AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(),
tasksResult.getFailed());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(),
tasksResult.getInProgress());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded(
operationResultPollResponse.getValue(), tasksResult.getCompleted());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(),
tasksResult.getTotal());
return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue()));
}
private Context getNotNullContext(Context context) {
return context == null ? Context.NONE : context;
}
private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) {
return options == null ? new AnalyzeActionsOptions() : options;
}
private String getNotNullModelVersion(String modelVersion) {
return modelVersion == null ? "latest" : modelVersion;
}
private String[] parseActionErrorTarget(String targetReference) {
if (CoreUtils.isNullOrEmpty(targetReference)) {
throw logger.logExceptionAsError(new RuntimeException(
"Expected an error with a target field referencing an action but did not get one"));
}
final Pattern pattern = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(targetReference);
String[] taskNameIdPair = new String[2];
while (matcher.find()) {
taskNameIdPair[0] = matcher.group(1);
taskNameIdPair[1] = matcher.group(2);
}
return taskNameIdPair;
}
} | class AnalyzeActionsAsyncClient {
private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks";
private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks";
private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks";
private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks";
private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks";
private static final String REGEX_ACTION_ERROR_TARGET = "
+ "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)";
private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class);
private final TextAnalyticsClientImpl service;
private static final Pattern PATTERN;
static {
PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE);
}
AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
PollerFlux<AnalyzeActionsOperationDetail, PagedFlux<AnalyzeActionsResult>> beginAnalyzeActions(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail textAnalyticsOperationResult =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper
.setOperationId(textAnalyticsOperationResult,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return textAnalyticsOperationResult;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext)))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
PollerFlux<AnalyzeActionsOperationDetail, PagedIterable<AnalyzeActionsResult>> beginAnalyzeActionsIterable(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail operationDetail =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return operationDetail;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperationIterable(operationId -> Mono.just(new PagedIterable<>(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext))))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>>
activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) {
return pollingContext -> {
try {
return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>>
pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) {
return pollingContext -> {
try {
final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse =
pollingContext.getLatestResponse();
final String operationId = operationResultPollResponse.getValue().getOperationId();
return pollingFunction.apply(operationId)
.flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse))
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PagedFlux<AnalyzeActionsResult>>>
fetchingOperation(Function<String, Mono<PagedFlux<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PagedIterable<AnalyzeActionsResult>>>
fetchingOperationIterable(Function<String, Mono<PagedIterable<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
PagedFlux<AnalyzeActionsResult> getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip,
boolean showStats, Context context) {
return new PagedFlux<>(
() -> getPage(null, operationId, top, skip, showStats, context),
continuationToken -> getPage(continuationToken, operationId, top, skip, showStats, context));
}
Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top,
Integer skip, boolean showStats, Context context) {
if (continuationToken != null) {
final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken);
final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null);
final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null);
final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false);
return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} else {
return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
}
}
private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) {
final AnalyzeJobState analyzeJobState = response.getValue();
return new PagedResponseBase<Void, AnalyzeActionsResult>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
Arrays.asList(toAnalyzeActionsResult(analyzeJobState)),
analyzeJobState.getNextLink(),
null);
}
private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) {
TasksStateTasks tasksStateTasks = analyzeJobState.getTasks();
final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems =
tasksStateTasks.getEntityRecognitionPiiTasks();
final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems =
tasksStateTasks.getEntityRecognitionTasks();
final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks =
tasksStateTasks.getKeyPhraseExtractionTasks();
final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems =
tasksStateTasks.getEntityLinkingTasks();
final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems =
tasksStateTasks.getSentimentAnalysisTasks();
List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>();
List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>();
List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>();
List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>();
List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>();
if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) {
for (int i = 0; i < entityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i);
final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult();
final EntitiesResult results = taskItem.getResults();
if (results != null) {
RecognizeEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizeEntitiesResultCollectionResponse(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(piiTasksItems)) {
for (int i = 0; i < piiTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i);
final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult();
final PiiResult results = taskItem.getResults();
if (results != null) {
RecognizePiiEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizePiiEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizePiiEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) {
for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) {
final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i);
final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult();
final KeyPhraseResult results = taskItem.getResults();
if (results != null) {
ExtractKeyPhrasesActionResultPropertiesHelper.setResult(actionResult,
toExtractKeyPhrasesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
extractKeyPhrasesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) {
for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i);
final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult();
final EntityLinkingResult results = taskItem.getResults();
if (results != null) {
RecognizeLinkedEntitiesActionResultPropertiesHelper.setResult(actionResult,
toRecognizeLinkedEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeLinkedEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) {
for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) {
final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i);
final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult();
final SentimentResponse results = taskItem.getResults();
if (results != null) {
AnalyzeSentimentActionResultPropertiesHelper.setResult(actionResult,
toAnalyzeSentimentResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
analyzeSentimentActionResults.add(actionResult);
}
}
final List<TextAnalyticsError> errors = analyzeJobState.getErrors();
if (!CoreUtils.isNullOrEmpty(errors)) {
for (TextAnalyticsError error : errors) {
final String[] targetPair = parseActionErrorTarget(error.getTarget());
final String taskName = targetPair[0];
final Integer taskIndex = Integer.valueOf(targetPair[1]);
final TextAnalyticsActionResult actionResult;
if (ENTITY_RECOGNITION_TASKS.equals(taskName)) {
actionResult = recognizeEntitiesActionResults.get(taskIndex);
} else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) {
actionResult = recognizePiiEntitiesActionResults.get(taskIndex);
} else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) {
actionResult = extractKeyPhrasesActionResults.get(taskIndex);
} else if (ENTITY_LINKING_TASKS.equals(taskName)) {
actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex);
} else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) {
actionResult = analyzeSentimentActionResults.get(taskIndex);
} else {
throw logger.logExceptionAsError(new RuntimeException(
"Invalid task name in target reference, " + taskName));
}
TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true);
TextAnalyticsActionResultPropertiesHelper.setError(actionResult,
new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(
error.getCode() == null ? null : error.getCode().toString()),
error.getMessage(), null));
}
}
final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult();
final RequestStatistics requestStatistics = analyzeJobState.getStatistics();
TextDocumentBatchStatistics batchStatistics = null;
if (requestStatistics != null) {
batchStatistics = new TextDocumentBatchStatistics(
requestStatistics.getDocumentsCount(), requestStatistics.getErroneousDocumentsCount(),
requestStatistics.getValidDocumentsCount(), requestStatistics.getTransactionsCount()
);
}
AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, batchStatistics);
AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizePiiEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult,
IterableStream.of(extractKeyPhrasesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeLinkedEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult,
IterableStream.of(analyzeSentimentActionResults));
return analyzeActionsResult;
}
private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse(
Response<AnalyzeJobState> analyzeJobStateResponse,
PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) {
LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) {
switch (analyzeJobStateResponse.getValue().getStatus()) {
case NOT_STARTED:
case RUNNING:
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case SUCCEEDED:
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case CANCELLED:
status = LongRunningOperationStatus.USER_CANCELLED;
break;
default:
status = LongRunningOperationStatus.fromString(
analyzeJobStateResponse.getValue().getStatus().toString(), true);
break;
}
}
AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getDisplayName());
AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getCreatedDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getExpirationDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getLastUpdateDateTime());
final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks();
AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(),
tasksResult.getFailed());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(),
tasksResult.getInProgress());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded(
operationResultPollResponse.getValue(), tasksResult.getCompleted());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(),
tasksResult.getTotal());
return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue()));
}
private Context getNotNullContext(Context context) {
return context == null ? Context.NONE : context;
}
private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) {
return options == null ? new AnalyzeActionsOptions() : options;
}
private String[] parseActionErrorTarget(String targetReference) {
if (CoreUtils.isNullOrEmpty(targetReference)) {
throw logger.logExceptionAsError(new RuntimeException(
"Expected an error with a target field referencing an action but did not get one"));
}
final Matcher matcher = PATTERN.matcher(targetReference);
String[] taskNameIdPair = new String[2];
while (matcher.find()) {
taskNameIdPair[0] = matcher.group(1);
taskNameIdPair[1] = matcher.group(2);
}
return taskNameIdPair;
}
} |
the behavior that was here before was making `this.recognizeEntitiesOptions` null too? or an empty list? | public TextAnalyticsActions setRecognizeEntitiesOptions(RecognizeEntitiesOptions... recognizeEntitiesOptions) {
this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null
: Arrays.asList(recognizeEntitiesOptions);
return this;
} | this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null | public TextAnalyticsActions setRecognizeEntitiesOptions(RecognizeEntitiesOptions... recognizeEntitiesOptions) {
this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null
: Arrays.asList(recognizeEntitiesOptions);
return this;
} | class TextAnalyticsActions {
private String displayName;
private Iterable<RecognizeEntitiesOptions> recognizeEntitiesOptions;
private Iterable<RecognizeLinkedEntitiesOptions> recognizeLinkedEntitiesOptions;
private Iterable<RecognizePiiEntitiesOptions> recognizePiiEntitiesOptions;
private Iterable<ExtractKeyPhrasesOptions> extractKeyPhrasesOptions;
private Iterable<AnalyzeSentimentOptions> analyzeSentimentOptions;
/**
* Get the custom name for the actions.
*
* @return the custom name for the actions.
*/
public String getDisplayName() {
return displayName;
}
/**
* Set the custom name for the actions.
*
* @param displayName the custom name for the actions.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizeEntitiesOptions} to be executed.
*/
public Iterable<RecognizeEntitiesOptions> getRecognizeEntitiesOptions() {
return this.recognizeEntitiesOptions;
}
/**
* Set the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @param recognizeEntitiesOptions the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizeLinkedEntitiesOptions> getRecognizeLinkedEntitiesOptions() {
return this.recognizeLinkedEntitiesOptions;
}
/**
* Set the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @param recognizeLinkedEntitiesOptions the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizeLinkedEntitiesOptions(
RecognizeLinkedEntitiesOptions... recognizeLinkedEntitiesOptions) {
this.recognizeLinkedEntitiesOptions = recognizeLinkedEntitiesOptions == null ? null
: Arrays.asList(recognizeLinkedEntitiesOptions);
return this;
}
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizePiiEntitiesOptions> getRecognizePiiEntitiesOptions() {
return this.recognizePiiEntitiesOptions;
}
/**
* Set the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @param recognizePiiEntitiesOptions the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizePiiEntitiesOptions(
RecognizePiiEntitiesOptions... recognizePiiEntitiesOptions) {
this.recognizePiiEntitiesOptions = recognizePiiEntitiesOptions == null ? null
: Arrays.asList(recognizePiiEntitiesOptions);
return this;
}
/**
* Get the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the list of {@link ExtractKeyPhrasesOptions} to be executed.
*/
public Iterable<ExtractKeyPhrasesOptions> getExtractKeyPhrasesOptions() {
return this.extractKeyPhrasesOptions;
}
/**
* Set the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @param extractKeyPhrasesOptions the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setExtractKeyPhrasesOptions(ExtractKeyPhrasesOptions... extractKeyPhrasesOptions) {
this.extractKeyPhrasesOptions = extractKeyPhrasesOptions == null ? null
: Arrays.asList(extractKeyPhrasesOptions);
return this;
}
/**
* Get the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the list of {@link AnalyzeSentimentOptions} to be executed.
*/
public Iterable<AnalyzeSentimentOptions> getAnalyzeSentimentOptions() {
return this.analyzeSentimentOptions;
}
/**
* Set the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @param analyzeSentimentOptions the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setAnalyzeSentimentOptions(AnalyzeSentimentOptions... analyzeSentimentOptions) {
this.analyzeSentimentOptions = analyzeSentimentOptions == null ? null : Arrays.asList(analyzeSentimentOptions);
return this;
}
} | class TextAnalyticsActions {
private String displayName;
private Iterable<RecognizeEntitiesOptions> recognizeEntitiesOptions;
private Iterable<RecognizeLinkedEntitiesOptions> recognizeLinkedEntitiesOptions;
private Iterable<RecognizePiiEntitiesOptions> recognizePiiEntitiesOptions;
private Iterable<ExtractKeyPhrasesOptions> extractKeyPhrasesOptions;
private Iterable<AnalyzeSentimentOptions> analyzeSentimentOptions;
/**
* Get the custom name for the actions.
*
* @return the custom name for the actions.
*/
public String getDisplayName() {
return displayName;
}
/**
* Set the custom name for the actions.
*
* @param displayName the custom name for the actions.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizeEntitiesOptions} to be executed.
*/
public Iterable<RecognizeEntitiesOptions> getRecognizeEntitiesOptions() {
return this.recognizeEntitiesOptions;
}
/**
* Set the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @param recognizeEntitiesOptions the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizeLinkedEntitiesOptions> getRecognizeLinkedEntitiesOptions() {
return this.recognizeLinkedEntitiesOptions;
}
/**
* Set the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @param recognizeLinkedEntitiesOptions the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizeLinkedEntitiesOptions(
RecognizeLinkedEntitiesOptions... recognizeLinkedEntitiesOptions) {
this.recognizeLinkedEntitiesOptions = recognizeLinkedEntitiesOptions == null ? null
: Arrays.asList(recognizeLinkedEntitiesOptions);
return this;
}
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizePiiEntitiesOptions> getRecognizePiiEntitiesOptions() {
return this.recognizePiiEntitiesOptions;
}
/**
* Set the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @param recognizePiiEntitiesOptions the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizePiiEntitiesOptions(
RecognizePiiEntitiesOptions... recognizePiiEntitiesOptions) {
this.recognizePiiEntitiesOptions = recognizePiiEntitiesOptions == null ? null
: Arrays.asList(recognizePiiEntitiesOptions);
return this;
}
/**
* Get the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the list of {@link ExtractKeyPhrasesOptions} to be executed.
*/
public Iterable<ExtractKeyPhrasesOptions> getExtractKeyPhrasesOptions() {
return this.extractKeyPhrasesOptions;
}
/**
* Set the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @param extractKeyPhrasesOptions the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setExtractKeyPhrasesOptions(ExtractKeyPhrasesOptions... extractKeyPhrasesOptions) {
this.extractKeyPhrasesOptions = extractKeyPhrasesOptions == null ? null
: Arrays.asList(extractKeyPhrasesOptions);
return this;
}
/**
* Get the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the list of {@link AnalyzeSentimentOptions} to be executed.
*/
public Iterable<AnalyzeSentimentOptions> getAnalyzeSentimentOptions() {
return this.analyzeSentimentOptions;
}
/**
* Set the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @param analyzeSentimentOptions the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setAnalyzeSentimentOptions(AnalyzeSentimentOptions... analyzeSentimentOptions) {
this.analyzeSentimentOptions = analyzeSentimentOptions == null ? null : Arrays.asList(analyzeSentimentOptions);
return this;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.