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 |
|---|---|---|---|---|---|
please add some comments here or on the method, to explain why we are using obo as defult. | public List<ClientRegistration> createClients() {
List<ClientRegistration> result = new ArrayList<>();
for (String id : properties.getAuthorizationClients().keySet()) {
AuthorizationClientProperties authorizationProperties = properties.getAuthorizationClients().get(id);
if (authorizationProperties.getAuthorizationGrantType() == null) {
authorizationProperties.setAuthorizationGrantType(AADAuthorizationGrantType.ON_BEHALF_OF
.getValue());
result.add(createOboClientBuilder(id, authorizationProperties));
} else if (authorizationProperties.getAuthorizationGrantType().equals(AADAuthorizationGrantType
.CLIENT_CREDENTIALS.getValue())) {
result.add(createWebClientBuilder(id, authorizationProperties));
}
}
return result;
} | if (authorizationProperties.getAuthorizationGrantType() == null) { | public List<ClientRegistration> createClients() {
List<ClientRegistration> result = new ArrayList<>();
for (String id : properties.getAuthorizationClients().keySet()) {
AuthorizationClientProperties authorizationProperties = properties.getAuthorizationClients().get(id);
if (authorizationProperties.getAuthorizationGrantType() == null || AADAuthorizationGrantType.ON_BEHALF_OF
.equals(authorizationProperties.getAuthorizationGrantType())) {
result.add(createOboClientBuilder(id, authorizationProperties));
} else if (AADAuthorizationGrantType.CLIENT_CREDENTIALS
.equals(authorizationProperties.getAuthorizationGrantType())) {
result.add(createWebClientBuilder(id, authorizationProperties));
}
}
return result;
} | class })
public ClientRegistrationRepository clientRegistrationRepository() {
final List<ClientRegistration> oboClients = createClients();
if (oboClients.isEmpty()) {
LOGGER.warn("No client registrations are found for AAD Client.");
return registrationId -> null;
}
return new InMemoryClientRegistrationRepository(oboClients);
} | class })
public ClientRegistrationRepository clientRegistrationRepository() {
final List<ClientRegistration> clients = createClients();
if (clients.isEmpty()) {
LOGGER.warn("No client registrations are found for AAD Client.");
return registrationId -> null;
}
return new InMemoryClientRegistrationRepository(clients);
} |
principal -->mockPrincipal | public void setup() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
addInlinedPropertiesToEnvironment(
context,
AAD_PROPERTY_PREFIX + "tenant-id = fake-tenant-id",
AAD_PROPERTY_PREFIX + "client-id = fake-client-id",
AAD_PROPERTY_PREFIX + "client-secret = fake-client-secret",
AAD_PROPERTY_PREFIX + "authorization-clients.fake.scopes = https:
+ ".com/xxxx-xxxxx-xxxx/.default",
AAD_PROPERTY_PREFIX + "authorization-clients.fake.authorization-grant-type = client_credentials"
);
context.register(AADResourceServerClientConfiguration.class);
context.refresh();
clientRegistrationsRepo = context.getBean(InMemoryClientRegistrationRepository.class);
fake = ClientRegistration
.withRegistrationId("fake")
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.tokenUri("https:
.scope("https:
.clientId("xxxx-xxxxx-xxxx").build();
OAuth2AccessToken oAuth2AccessToken = mock(OAuth2AccessToken.class);
when(oAuth2AccessToken.getTokenValue()).thenReturn(CLIENT_CREDENTIAL_ACCESS_TOKEN);
oAuth2AuthorizedClient = new OAuth2AuthorizedClient(fake, "fake-name", oAuth2AccessToken);
principal = mock(JwtAuthenticationToken.class);
when(principal.getName()).thenReturn("fake-name");
inMemoryOAuth2AuthorizedClientService = new InMemoryOAuth2AuthorizedClientService(clientRegistrationsRepo);
authorizedRepo = new AADResourceServerOAuth2AuthorizedClientRepository(inMemoryOAuth2AuthorizedClientService,
clientRegistrationsRepo);
authorizedRepo.saveAuthorizedClient(oAuth2AuthorizedClient, principal, request, response);
} | principal = mock(JwtAuthenticationToken.class); | public void setup() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
addInlinedPropertiesToEnvironment(
context,
AAD_PROPERTY_PREFIX + "tenant-id = fake-tenant-id",
AAD_PROPERTY_PREFIX + "client-id = fake-client-id",
AAD_PROPERTY_PREFIX + "client-secret = fake-client-secret",
AAD_PROPERTY_PREFIX + "authorization-clients.fake.scopes = https:
+ ".com/xxxx-xxxxx-xxxx/.default",
AAD_PROPERTY_PREFIX + "authorization-clients.fake.authorization-grant-type = client_credentials"
);
context.register(AADResourceServerClientConfiguration.class);
context.refresh();
clientRegistrationsRepo = context.getBean(InMemoryClientRegistrationRepository.class);
fakeClientRegistration = ClientRegistration
.withRegistrationId("fake")
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.tokenUri("https:
.scope("https:
.clientId("xxxx-xxxxx-xxxx").build();
OAuth2AccessToken mockOAuth2AccessToken = mock(OAuth2AccessToken.class);
when(mockOAuth2AccessToken.getTokenValue()).thenReturn(CLIENT_CREDENTIAL_ACCESS_TOKEN);
oAuth2AuthorizedClient = new OAuth2AuthorizedClient(fakeClientRegistration, "fake-name", mockOAuth2AccessToken);
mockPrincipal = mock(JwtAuthenticationToken.class);
when(mockPrincipal.getName()).thenReturn("fake-name");
inMemoryOAuth2AuthorizedClientService = new InMemoryOAuth2AuthorizedClientService(clientRegistrationsRepo);
authorizedRepo = new AADResourceServerOAuth2AuthorizedClientRepository(inMemoryOAuth2AuthorizedClientService,
clientRegistrationsRepo);
authorizedRepo.saveAuthorizedClient(oAuth2AuthorizedClient, mockPrincipal, mockRequest, mockResponse);
} | class AADOAuth2AuthorizedClientCredentialRepositoryTest {
private static final String AAD_PROPERTY_PREFIX = "azure.activedirectory.";
private static final String CLIENT_CREDENTIAL_ACCESS_TOKEN =
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyIsImtpZCI6Im5PbzNaRHJPRFhFSz"
+ "FqS1doWHNsSFJfS1hFZyJ9.eyJhdWQiOiJhcGk6Ly85MjdiYTU0Mi05YWRmLTQxMzktOWI3Yy03ZDA0MmM0YWVhMTUiLCJpc3MiOiJod"
+ "HRwczovL3N0cy53aW5kb3dzLm5ldC8xYzA1N2U3Yy01NGQ5LTRiNTItODkwMi05ZTE2Yjc0ODVkMzUvIiwiaWF0IjoxNjE1NTE1OTY2L"
+ "CJuYmYiOjE2MTU1MTU5NjYsImV4cCI6MTYxNTUxOTg2NiwiYWNyIjoiMSIsImFpbyI6IkFUUUF5LzhUQUFBQWJyNGk5SnBvYlNjdUltN"
+ "2ZSQjFuNzUzVHg2VzZrVkFzZVZtOXV0ODVIT1BGTk9WRllkSWt3eUpNeTVuMlByTGciLCJhbXIiOlsicHdkIl0sImFwcGlkIjoiOTExN"
+ "2QxZjEtNDE2Ny00MWE3LWFiMDUtNzNlZDRiZmUwOTg4IiwiYXBwaWRhY3IiOiIxIiwiaXBhZGRyIjoiMTY3LjIyMC4yNTUuOCIsIm5hb"
+ "WUiOiJhcHBfdXNlciIsIm9pZCI6IjUzNTcwM2EyLTY0MGMtNDM0NS04YmE4LTNjMGU1ZTQ0N2RhYyIsInB3ZF9leHAiOiIxMDM0ODYyI"
+ "iwicHdkX3VybCI6Imh0dHBzOi8vcG9ydGFsLm1pY3Jvc29mdG9ubGluZS5jb20vQ2hhbmdlUGFzc3dvcmQuYXNweCIsInJoIjoiMC5BQ"
+ "UFBZkg0RkhObFVVa3VKQXA0V3QwaGROZkhSRjVGblFhZEJxd1Z6N1V2LUNZaDRBSncuIiwic2NwIjoiRmlsZS5yZWFkIiwic3ViIjoiS"
+ "DNnV1YyLVJrODJBZHF0a3VyVzlvdVFPZmVRRDJ1NXZ3MkdIcWZRSWlfOCIsInRpZCI6IjFjMDU3ZTdjLTU0ZDktNGI1Mi04OTAyLTllM"
+ "TZiNzQ4NWQzNSIsInVuaXF1ZV9uYW1lIjoiYXBwX3VzZXJAeGlhb3podXRlc3RzYW1wbGUub25taWNyb3NvZnQuY29tIiwidXBuIjoiY"
+ "XBwX3VzZXJAeGlhb3podXRlc3RzYW1wbGUub25taWNyb3NvZnQuY29tIiwidXRpIjoiNTcyZERTQ2Vta2VETkxOUVRXRUVBQSIsInZlc"
+ "iI6IjEuMCJ9.TLE8oRV-6h3MKVyUDgRdNw-VuPjuZMIbe9QxQMUwMDLFPlnPBZizYaM9tcGGUvIWuBV_rQkayHPHRbVhOUqFTwQyiv1Z"
+ "hBUbXgltBzDt5rybd2rh0O6HsNqZGTYD65lMMnd_TvpFf2hBpvf1q9C-Txa2HRx8Q4i6Q3gAKCjcxbEMITwLlCMz3JtTQ785lME9o4fZ"
+ "R-s_LOz1eBiMboKWIPiQZwWQ-peGNsalNriss4_x4pwOwYlMqeZJBk1tIyON0nYNLTU169_KSGHIlTtVtaAlNnt9C2Ajg1PTvJvj3fsg"
+ "FhZpRbO4XBs6nEjFSwPC0RII36raH9wjgveNn63LPg";
private ClientRegistration fake;
private Authentication principal;
private OAuth2AuthorizedClient oAuth2AuthorizedClient;
private InMemoryClientRegistrationRepository clientRegistrationsRepo;
private AADResourceServerOAuth2AuthorizedClientRepository authorizedRepo;
private InMemoryOAuth2AuthorizedClientService inMemoryOAuth2AuthorizedClientService;
private HttpServletRequest request = mock(MockHttpServletRequest.class);
private HttpServletResponse response = mock(MockHttpServletResponse.class);
@BeforeEach
@Test
public void testAuthorizedClientCache() {
OAuth2AuthorizedClient authorizedClient = inMemoryOAuth2AuthorizedClientService
.loadAuthorizedClient(fake.getRegistrationId(), "fake-name");
Assertions.assertNotNull(authorizedClient);
Assertions.assertEquals(CLIENT_CREDENTIAL_ACCESS_TOKEN, authorizedClient.getAccessToken().getTokenValue());
}
@Test
public void testLoadAuthorizedClient() {
OAuth2AuthorizedClient authorizedClient = authorizedRepo.loadAuthorizedClient(
"fake", principal, request);
Assertions.assertNotNull(authorizedClient);
Assertions.assertEquals(CLIENT_CREDENTIAL_ACCESS_TOKEN, authorizedClient.getAccessToken().getTokenValue());
}
@Test
public void testLoadNotExistAuthorizedClient() {
OAuth2AuthorizedClient authorizedClient = authorizedRepo.loadAuthorizedClient(
"fake-2", principal, request);
Assertions.assertNull(authorizedClient);
}
} | class AADOAuth2AuthorizedClientCredentialRepositoryTest {
private static final String AAD_PROPERTY_PREFIX = "azure.activedirectory.";
private static final String CLIENT_CREDENTIAL_ACCESS_TOKEN =
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyIsImtpZCI6Im5PbzNaRHJPRFhFSz"
+ "FqS1doWHNsSFJfS1hFZyJ9.eyJhdWQiOiJhcGk6Ly85MjdiYTU0Mi05YWRmLTQxMzktOWI3Yy03ZDA0MmM0YWVhMTUiLCJpc3MiOiJod"
+ "HRwczovL3N0cy53aW5kb3dzLm5ldC8xYzA1N2U3Yy01NGQ5LTRiNTItODkwMi05ZTE2Yjc0ODVkMzUvIiwiaWF0IjoxNjE1NTE1OTY2L"
+ "CJuYmYiOjE2MTU1MTU5NjYsImV4cCI6MTYxNTUxOTg2NiwiYWNyIjoiMSIsImFpbyI6IkFUUUF5LzhUQUFBQWJyNGk5SnBvYlNjdUltN"
+ "2ZSQjFuNzUzVHg2VzZrVkFzZVZtOXV0ODVIT1BGTk9WRllkSWt3eUpNeTVuMlByTGciLCJhbXIiOlsicHdkIl0sImFwcGlkIjoiOTExN"
+ "2QxZjEtNDE2Ny00MWE3LWFiMDUtNzNlZDRiZmUwOTg4IiwiYXBwaWRhY3IiOiIxIiwiaXBhZGRyIjoiMTY3LjIyMC4yNTUuOCIsIm5hb"
+ "WUiOiJhcHBfdXNlciIsIm9pZCI6IjUzNTcwM2EyLTY0MGMtNDM0NS04YmE4LTNjMGU1ZTQ0N2RhYyIsInB3ZF9leHAiOiIxMDM0ODYyI"
+ "iwicHdkX3VybCI6Imh0dHBzOi8vcG9ydGFsLm1pY3Jvc29mdG9ubGluZS5jb20vQ2hhbmdlUGFzc3dvcmQuYXNweCIsInJoIjoiMC5BQ"
+ "UFBZkg0RkhObFVVa3VKQXA0V3QwaGROZkhSRjVGblFhZEJxd1Z6N1V2LUNZaDRBSncuIiwic2NwIjoiRmlsZS5yZWFkIiwic3ViIjoiS"
+ "DNnV1YyLVJrODJBZHF0a3VyVzlvdVFPZmVRRDJ1NXZ3MkdIcWZRSWlfOCIsInRpZCI6IjFjMDU3ZTdjLTU0ZDktNGI1Mi04OTAyLTllM"
+ "TZiNzQ4NWQzNSIsInVuaXF1ZV9uYW1lIjoiYXBwX3VzZXJAeGlhb3podXRlc3RzYW1wbGUub25taWNyb3NvZnQuY29tIiwidXBuIjoiY"
+ "XBwX3VzZXJAeGlhb3podXRlc3RzYW1wbGUub25taWNyb3NvZnQuY29tIiwidXRpIjoiNTcyZERTQ2Vta2VETkxOUVRXRUVBQSIsInZlc"
+ "iI6IjEuMCJ9.TLE8oRV-6h3MKVyUDgRdNw-VuPjuZMIbe9QxQMUwMDLFPlnPBZizYaM9tcGGUvIWuBV_rQkayHPHRbVhOUqFTwQyiv1Z"
+ "hBUbXgltBzDt5rybd2rh0O6HsNqZGTYD65lMMnd_TvpFf2hBpvf1q9C-Txa2HRx8Q4i6Q3gAKCjcxbEMITwLlCMz3JtTQ785lME9o4fZ"
+ "R-s_LOz1eBiMboKWIPiQZwWQ-peGNsalNriss4_x4pwOwYlMqeZJBk1tIyON0nYNLTU169_KSGHIlTtVtaAlNnt9C2Ajg1PTvJvj3fsg"
+ "FhZpRbO4XBs6nEjFSwPC0RII36raH9wjgveNn63LPg";
private ClientRegistration fakeClientRegistration;
private Authentication mockPrincipal;
private OAuth2AuthorizedClient oAuth2AuthorizedClient;
private InMemoryClientRegistrationRepository clientRegistrationsRepo;
private AADResourceServerOAuth2AuthorizedClientRepository authorizedRepo;
private InMemoryOAuth2AuthorizedClientService inMemoryOAuth2AuthorizedClientService;
private HttpServletRequest mockRequest = mock(MockHttpServletRequest.class);
private HttpServletResponse mockResponse = mock(MockHttpServletResponse.class);
@BeforeEach
@Test
public void testAuthorizedClientCache() {
OAuth2AuthorizedClient authorizedClient = inMemoryOAuth2AuthorizedClientService
.loadAuthorizedClient(fakeClientRegistration.getRegistrationId(), "fake-name");
Assertions.assertNotNull(authorizedClient);
Assertions.assertEquals(CLIENT_CREDENTIAL_ACCESS_TOKEN, authorizedClient.getAccessToken().getTokenValue());
}
@Test
public void testLoadAuthorizedClient() {
OAuth2AuthorizedClient authorizedClient = authorizedRepo.loadAuthorizedClient(
"fake", mockPrincipal, mockRequest);
Assertions.assertNotNull(authorizedClient);
Assertions.assertEquals(CLIENT_CREDENTIAL_ACCESS_TOKEN, authorizedClient.getAccessToken().getTokenValue());
}
@Test
public void testLoadNotExistAuthorizedClient() {
OAuth2AuthorizedClient authorizedClient = authorizedRepo.loadAuthorizedClient(
"fake-2", mockPrincipal, mockRequest);
Assertions.assertNull(authorizedClient);
}
} |
@ZhuXiaoBing-cn we need to address this comment https://github.com/Azure/azure-sdk-for-java/pull/19808/files/a379b85bc5d789983f70318c92247999f0567983#r595838276 | public List<ClientRegistration> createClients() {
List<ClientRegistration> result = new ArrayList<>();
for (String id : properties.getAuthorizationClients().keySet()) {
AuthorizationClientProperties authorizationProperties = properties.getAuthorizationClients().get(id);
if (authorizationProperties.getAuthorizationGrantType() == null) {
authorizationProperties.setAuthorizationGrantType(AADAuthorizationGrantType.ON_BEHALF_OF
.getValue());
result.add(createOboClientBuilder(id, authorizationProperties));
} else if (authorizationProperties.getAuthorizationGrantType().equals(AADAuthorizationGrantType
.CLIENT_CREDENTIALS.getValue())) {
result.add(createWebClientBuilder(id, authorizationProperties));
}
}
return result;
} | if (authorizationProperties.getAuthorizationGrantType() == null) { | public List<ClientRegistration> createClients() {
List<ClientRegistration> result = new ArrayList<>();
for (String id : properties.getAuthorizationClients().keySet()) {
AuthorizationClientProperties authorizationProperties = properties.getAuthorizationClients().get(id);
if (authorizationProperties.getAuthorizationGrantType() == null || AADAuthorizationGrantType.ON_BEHALF_OF
.equals(authorizationProperties.getAuthorizationGrantType())) {
result.add(createOboClientBuilder(id, authorizationProperties));
} else if (AADAuthorizationGrantType.CLIENT_CREDENTIALS
.equals(authorizationProperties.getAuthorizationGrantType())) {
result.add(createWebClientBuilder(id, authorizationProperties));
}
}
return result;
} | class })
public ClientRegistrationRepository clientRegistrationRepository() {
final List<ClientRegistration> oboClients = createClients();
if (oboClients.isEmpty()) {
LOGGER.warn("No client registrations are found for AAD Client.");
return registrationId -> null;
}
return new InMemoryClientRegistrationRepository(oboClients);
} | class })
public ClientRegistrationRepository clientRegistrationRepository() {
final List<ClientRegistration> clients = createClients();
if (clients.isEmpty()) {
LOGGER.warn("No client registrations are found for AAD Client.");
return registrationId -> null;
}
return new InMemoryClientRegistrationRepository(clients);
} |
Please check for status code 200 as well | public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
} | if (response.isPresent()) { | public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} |
We should check status code 404 on exception to determine collection does not exist, and for any other exception we should float the exception up | private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
} | return Optional.empty(); | private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
}
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
}
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} |
I had started down this path, but there are 2 possibilities in the event of an error (and in both cases it returns Optional.empty() 1. Collection does not exist 2. Collection exists, but there was another error In either case, the code will ahead and call createContainer, which uses createContainerIfNotExists to create the Collection. If there is an error on this call, then we throw the exception all the way up. To put my long answer differently: What's the impact/consequence of not checking for 404? | private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
} | return Optional.empty(); | private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
}
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
}
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} |
The presence/not present is handled with getContainerProperties. Any checks will have to happen there. Resolving this convo and moving to the other open conversation. | public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
} | if (response.isPresent()) { | public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} |
"Collection exists, but there was another error" in this case error could be anything so it is ideal to float the error right there instead of going further in the logic. In this case it is not a big deal as this is testing workload, so your call. But it is advisable to do the right error check in real prod application. | private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
} | return Optional.empty(); | private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
}
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
}
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} |
I agree if there is an error, there's not much value in continuing. | private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
} | return Optional.empty(); | private Optional<CosmosContainerResponse> getContainerProperties(CosmosAsyncContainer container) {
try {
return Optional.ofNullable(container.read().
block(RESOURCE_CRUD_WAIT_TIME));
} catch (CosmosException e) {
return Optional.empty();
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
}
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} | class CollectionResourceManager implements ResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionResourceManager.class);
private static final Duration RESOURCE_CRUD_WAIT_TIME = Duration.ofSeconds(30);
private final Configuration _configuration;
private final EntityConfiguration _entityConfiguration;
private final CosmosAsyncClient _client;
public CollectionResourceManager(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
Preconditions.checkNotNull(entityConfiguration,
"The Test Entity specific configuration can not be null");
Preconditions.checkNotNull(client, "Need a non-null client for "
+ "setting up the Database and collections for the test");
_configuration = configuration;
_entityConfiguration = entityConfiguration;
_client = client;
}
@Override
public void createResources() throws CosmosException {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
try {
LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
final CosmosAsyncContainer container = database.getContainer(containerName);
final Optional<CosmosContainerResponse> response = getContainerProperties(container);
if (response.isPresent()) {
LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
applyDesiredContainerPolicies(container, response.get().getProperties());
return;
}
createContainer(database, containerName, collectionAttributes);
} catch (CosmosException e) {
LOGGER.error("Exception while configuring collection {}", containerName, e);
throw e;
}
}
@Override
public void deleteResources() {
LOGGER.info("The Collection {} will not be deleted.", _configuration.getCollectionId());
}
private void applyDesiredContainerPolicies(final CosmosAsyncContainer container,
final CosmosContainerProperties properties) {
LOGGER.info("Updating container {} properties to desired", container.getId());
properties.setIndexingPolicy(_entityConfiguration.collectionAttributes().indexingPolicy());
container.replace(properties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
private void createContainer(final CosmosAsyncDatabase database,
final String containerName,
final CollectionAttributes collectionAttributes) {
LOGGER.info("Creating container {} in the database {}", containerName, database.getId());
final CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, Constants.PARTITION_KEY_PATH)
.setIndexingPolicy(collectionAttributes.indexingPolicy());
database.createContainerIfNotExists(containerProperties)
.block(RESOURCE_CRUD_WAIT_TIME);
}
} |
What is this doing? Why do we null check and just do a get without assigning it to anything or doing anything with the return value? | void dispose(ErrorCondition errorCondition) {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("connectionId[{}], sessionId[{}], errorCondition[{}]: Disposing of session.",
sessionHandler.getConnectionId(), sessionName, errorCondition != null ? errorCondition : NOT_APPLICABLE);
if (session.getLocalState() != EndpointState.CLOSED) {
session.close();
if (session.getCondition() == null) {
session.setCondition(errorCondition);
}
}
openReceiveLinks.forEach((key, link) -> link.dispose(errorCondition));
openSendLinks.forEach((key, link) -> link.dispose(errorCondition));
if (transactionCoordinator.get() != null) {
transactionCoordinator.get();
}
} | } | void dispose(ErrorCondition errorCondition) {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("connectionId[{}], sessionId[{}], errorCondition[{}]: Disposing of session.",
sessionHandler.getConnectionId(), sessionName, errorCondition != null ? errorCondition : NOT_APPLICABLE);
if (session.getLocalState() != EndpointState.CLOSED) {
session.close();
if (session.getCondition() == null) {
session.setCondition(errorCondition);
}
}
openReceiveLinks.forEach((key, link) -> link.dispose(errorCondition));
openSendLinks.forEach((key, link) -> link.dispose(errorCondition));
} | class ReactorSession implements AmqpSession {
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final ConcurrentMap<String, LinkSubscription<AmqpSendLink>> openSendLinks = new ConcurrentHashMap<>();
private final ConcurrentMap<String, LinkSubscription<AmqpReceiveLink>> openReceiveLinks = new ConcurrentHashMap<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final ClientLogger logger = new ClientLogger(ReactorSession.class);
private final ReplayProcessor<AmqpEndpointState> endpointStates;
private final Session session;
private final SessionHandler sessionHandler;
private final String sessionName;
private final ReactorProvider provider;
private final TokenManagerProvider tokenManagerProvider;
private final MessageSerializer messageSerializer;
private final String activeTimeoutMessage;
private final AmqpRetryOptions retryOptions;
private final ReactorHandlerProvider handlerProvider;
private final Mono<ClaimsBasedSecurityNode> cbsNodeSupplier;
private final AtomicReference<TransactionCoordinator> transactionCoordinator = new AtomicReference<>();
/**
* Creates a new AMQP session using proton-j.
*
* @param session Proton-j session for this AMQP session.
* @param sessionHandler Handler for events that occur in the session.
* @param sessionName Name of the session.
* @param provider Provides reactor instances for messages to sent with.
* @param handlerProvider Providers reactor handlers for listening to proton-j reactor events.
* @param cbsNodeSupplier Mono that returns a reference to the {@link ClaimsBasedSecurityNode}.
* @param tokenManagerProvider Provides {@link TokenManager} that authorizes the client when performing
* operations on the message broker.
* @param retryOptions for the session operations.
*/
public ReactorSession(Session session, SessionHandler sessionHandler, String sessionName, ReactorProvider provider,
ReactorHandlerProvider handlerProvider, Mono<ClaimsBasedSecurityNode> cbsNodeSupplier,
TokenManagerProvider tokenManagerProvider, MessageSerializer messageSerializer,
AmqpRetryOptions retryOptions) {
this.session = session;
this.sessionHandler = sessionHandler;
this.handlerProvider = handlerProvider;
this.sessionName = sessionName;
this.provider = provider;
this.cbsNodeSupplier = cbsNodeSupplier;
this.tokenManagerProvider = tokenManagerProvider;
this.messageSerializer = messageSerializer;
this.retryOptions = retryOptions;
this.activeTimeoutMessage = String.format(
"ReactorSession connectionId[%s], session[%s]: Retries exhausted waiting for ACTIVE endpoint state.",
sessionHandler.getConnectionId(), sessionName);
this.endpointStates = sessionHandler.getEndpointStates()
.map(state -> {
logger.verbose("connectionId[{}], sessionName[{}], state[{}]", sessionHandler.getConnectionId(),
sessionName, state);
return AmqpEndpointStateUtil.getConnectionState(state);
})
.subscribeWith(ReplayProcessor.cacheLastOrDefault(AmqpEndpointState.UNINITIALIZED));
session.open();
}
Session session() {
return this.session;
}
@Override
public Flux<AmqpEndpointState> getEndpointStates() {
return endpointStates;
}
@Override
public boolean isDisposed() {
return isDisposed.get();
}
/**
* {@inheritDoc}
*/
@Override
public void dispose() {
dispose(null);
}
/**
* {@inheritDoc}
*/
@Override
public String getSessionName() {
return sessionName;
}
/**
* {@inheritDoc}
*/
@Override
public Duration getOperationTimeout() {
return retryOptions.getTryTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpTransaction> createTransaction() {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.declare());
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> commitTransaction(AmqpTransaction transaction) {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.discharge(transaction, true));
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> rollbackTransaction(AmqpTransaction transaction) {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.discharge(transaction, false));
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry) {
return createProducer(linkName, entityPath, timeout, retry, null);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpLink> createConsumer(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry) {
return createConsumer(linkName, entityPath, timeout, retry, null, null, null,
SenderSettleMode.UNSETTLED, ReceiverSettleMode.SECOND)
.cast(AmqpLink.class);
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeLink(String linkName) {
return removeLink(openSendLinks, linkName) || removeLink(openReceiveLinks, linkName);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpTransactionCoordinator> getOrCreateTransactionCoordinator() {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create coordinator send link '%s' from a closed session.", TRANSACTION_LINK_NAME))));
}
final TransactionCoordinator existing = transactionCoordinator.get();
if (existing != null) {
logger.verbose("Coordinator[{}]: Returning existing transaction coordinator.", TRANSACTION_LINK_NAME);
return Mono.just(existing);
}
return createProducer(TRANSACTION_LINK_NAME, TRANSACTION_LINK_NAME, new Coordinator(), retryOptions, null,
false)
.map(link -> {
final TransactionCoordinator newCoordinator = new TransactionCoordinator(link, messageSerializer);
if (transactionCoordinator.compareAndSet(null, newCoordinator)) {
return newCoordinator;
} else {
return transactionCoordinator.get();
}
});
}
/**
* Creates an {@link AmqpReceiveLink} that has AMQP specific capabilities set.
*
* Filters can be applied to the source when receiving to inform the source to filter the items sent to the
* consumer. See
* <a href="http:
* Messages</a> and <a href="https:
*
* @param linkName Name of the receive link.
* @param entityPath Address in the message broker for the link.
* @param timeout Operation timeout when creating the link.
* @param retry Retry policy to apply when link creation times out.
* @param sourceFilters Add any filters to the source when creating the receive link.
* @param receiverProperties Any properties to associate with the receive link when attaching to message
* broker.
* @param receiverDesiredCapabilities Capabilities that the receiver link supports.
* @param senderSettleMode Amqp {@link SenderSettleMode} mode for receiver.
* @param receiverSettleMode Amqp {@link ReceiverSettleMode} mode for receiver.
*
* @return A new instance of an {@link AmqpReceiveLink} with the correct properties set.
*/
protected Mono<AmqpReceiveLink> createConsumer(String linkName, String entityPath, Duration timeout,
AmqpRetryPolicy retry, Map<Symbol, Object> sourceFilters, Map<Symbol, Object> receiverProperties,
Symbol[] receiverDesiredCapabilities, SenderSettleMode senderSettleMode,
ReceiverSettleMode receiverSettleMode) {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create receive link '%s' from a closed session. entityPath[%s]", linkName, entityPath))));
}
final LinkSubscription<AmqpReceiveLink> existingLink = openReceiveLinks.get(linkName);
if (existingLink != null) {
logger.info("linkName[{}] entityPath[{}]: Returning existing receive link.", linkName, entityPath);
return Mono.just(existingLink.getLink());
}
final TokenManager tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath);
return Mono.when(onActiveEndpoint(), tokenManager.authorize()).then(Mono.create(sink -> {
try {
provider.getReactorDispatcher().invoke(() -> {
final LinkSubscription<AmqpReceiveLink> computed = openReceiveLinks.compute(linkName,
(linkNameKey, existing) -> {
if (existing != null) {
logger.info("linkName[{}]: Another receive link exists. Disposing of new one.",
linkName);
tokenManager.close();
return existing;
}
logger.info("Creating a new receiver link with linkName {}", linkName);
return getSubscription(linkNameKey, entityPath, sourceFilters, receiverProperties,
receiverDesiredCapabilities, senderSettleMode, receiverSettleMode, tokenManager);
});
sink.success(computed.getLink());
});
} catch (IOException e) {
sink.error(e);
}
}));
}
/**
* Given the entity path, associated receiver and link handler, creates the receive link instance.
*/
protected ReactorReceiver createConsumer(String entityPath, Receiver receiver,
ReceiveLinkHandler receiveLinkHandler, TokenManager tokenManager, ReactorProvider reactorProvider) {
return new ReactorReceiver(entityPath, receiver, receiveLinkHandler, tokenManager,
reactorProvider.getReactorDispatcher());
}
/**
* Creates an {@link AmqpLink} that has AMQP specific capabilities set.
*
* @param linkName Name of the receive link.
* @param entityPath Address in the message broker for the link.
* @param linkProperties The properties needed to be set on the link.
* @param timeout Operation timeout when creating the link.
* @param retry Retry policy to apply when link creation times out.
*
* @return A new instance of an {@link AmqpLink} with the correct properties set.
*/
protected Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout,
AmqpRetryPolicy retry, Map<Symbol, Object> linkProperties) {
final Target target = new Target();
target.setAddress(entityPath);
final AmqpRetryOptions options = retry != null
? new AmqpRetryOptions(retry.getRetryOptions())
: new AmqpRetryOptions();
if (timeout != null) {
options.setTryTimeout(timeout);
}
return createProducer(linkName, entityPath, target, options, linkProperties, true)
.cast(AmqpLink.class);
}
private Mono<AmqpSendLink> createProducer(String linkName, String entityPath,
org.apache.qpid.proton.amqp.transport.Target target, AmqpRetryOptions options,
Map<Symbol, Object> linkProperties, boolean requiresAuthorization) {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create send link '%s' from a closed session. entityPath[%s]", linkName, entityPath))));
}
final LinkSubscription<AmqpSendLink> existing = openSendLinks.get(linkName);
if (existing != null) {
logger.verbose("linkName[{}]: Returning existing send link.", linkName);
return Mono.just(existing.getLink());
}
final TokenManager tokenManager;
final Mono<Long> authorize;
if (requiresAuthorization) {
tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath);
authorize = tokenManager.authorize();
} else {
tokenManager = null;
authorize = Mono.empty();
}
return Mono.when(onActiveEndpoint(), authorize).then(Mono.create(sink -> {
try {
provider.getReactorDispatcher().invoke(() -> {
final LinkSubscription<AmqpSendLink> computed = openSendLinks.compute(linkName,
(linkNameKey, existingLink) -> {
if (existingLink != null) {
logger.info("linkName[{}]: Another send link exists. Disposing of new one.",
linkName);
if (tokenManager != null) {
tokenManager.close();
}
return existingLink;
}
logger.info("Creating a new sender link with linkName {}", linkName);
return getSubscription(linkName, entityPath, target, linkProperties, options,
tokenManager);
});
sink.success(computed.getLink());
});
} catch (IOException e) {
sink.error(e);
}
}));
}
/**
* NOTE: Ensure this is invoked using the reactor dispatcher because proton-j is not thread-safe.
*/
private LinkSubscription<AmqpSendLink> getSubscription(String linkName, String entityPath,
org.apache.qpid.proton.amqp.transport.Target target, Map<Symbol, Object> linkProperties,
AmqpRetryOptions options, TokenManager tokenManager) {
final Sender sender = session.sender(linkName);
sender.setTarget(target);
final Source source = new Source();
sender.setSource(source);
sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
if (linkProperties != null && linkProperties.size() > 0) {
sender.setProperties(linkProperties);
}
final SendLinkHandler sendLinkHandler = handlerProvider.createSendLinkHandler(
sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath);
BaseHandler.setHandler(sender, sendLinkHandler);
sender.open();
final ReactorSender reactorSender = new ReactorSender(entityPath, sender, sendLinkHandler, provider,
tokenManager, messageSerializer, options);
final Disposable subscription = reactorSender.getEndpointStates().subscribe(state -> {
}, error -> {
logger.info("linkName[{}]: Error occurred. Removing and disposing send link.",
linkName, error);
removeLink(openSendLinks, linkName);
}, () -> {
logger.info("linkName[{}]: Complete. Removing and disposing send link.", linkName);
removeLink(openSendLinks, linkName);
});
return new LinkSubscription<>(reactorSender, subscription);
}
/**
* NOTE: Ensure this is invoked using the reactor dispatcher because proton-j is not thread-safe.
*/
private LinkSubscription<AmqpReceiveLink> getSubscription(String linkName, String entityPath,
Map<Symbol, Object> sourceFilters, Map<Symbol, Object> receiverProperties,
Symbol[] receiverDesiredCapabilities, SenderSettleMode senderSettleMode, ReceiverSettleMode receiverSettleMode,
TokenManager tokenManager) {
final Receiver receiver = session.receiver(linkName);
final Source source = new Source();
source.setAddress(entityPath);
if (sourceFilters != null && sourceFilters.size() > 0) {
source.setFilter(sourceFilters);
}
receiver.setSource(source);
final Target target = new Target();
receiver.setTarget(target);
receiver.setSenderSettleMode(senderSettleMode);
receiver.setReceiverSettleMode(receiverSettleMode);
if (receiverProperties != null && !receiverProperties.isEmpty()) {
receiver.setProperties(receiverProperties);
}
if (receiverDesiredCapabilities != null && receiverDesiredCapabilities.length > 0) {
receiver.setDesiredCapabilities(receiverDesiredCapabilities);
}
final ReceiveLinkHandler receiveLinkHandler = handlerProvider.createReceiveLinkHandler(
sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath);
BaseHandler.setHandler(receiver, receiveLinkHandler);
receiver.open();
final ReactorReceiver reactorReceiver = createConsumer(entityPath, receiver, receiveLinkHandler,
tokenManager, provider);
final Disposable subscription = reactorReceiver.getEndpointStates().subscribe(state -> {
}, error -> {
logger.info(
"linkName[{}] entityPath[{}]: Error occurred. Removing receive link.",
linkName, entityPath, error);
removeLink(openReceiveLinks, linkName);
}, () -> {
logger.info("linkName[{}] entityPath[{}]: Complete. Removing receive link.",
linkName, entityPath);
removeLink(openReceiveLinks, linkName);
});
return new LinkSubscription<>(reactorReceiver, subscription);
}
/**
* Asynchronously waits for the session's active endpoint state.
*
* @return A mono that completes when the session is active.
*/
private Mono<Void> onActiveEndpoint() {
return RetryUtil.withRetry(getEndpointStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE),
retryOptions, activeTimeoutMessage)
.then();
}
private <T extends AmqpLink> boolean removeLink(ConcurrentMap<String, LinkSubscription<T>> openLinks, String key) {
if (key == null) {
return false;
}
final LinkSubscription<T> removed = openLinks.remove(key);
if (removed != null) {
removed.dispose(null);
}
return removed != null;
}
private static final class LinkSubscription<T extends AmqpLink> {
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final T link;
private final Disposable subscription;
private LinkSubscription(T link, Disposable subscription) {
this.link = link;
this.subscription = subscription;
}
public T getLink() {
return link;
}
void dispose(ErrorCondition errorCondition) {
if (isDisposed.getAndSet(true)) {
return;
}
if (link instanceof ReactorReceiver) {
final ReactorReceiver reactorReceiver = (ReactorReceiver) link;
reactorReceiver.dispose(errorCondition);
} else if (link instanceof ReactorSender) {
final ReactorSender reactorSender = (ReactorSender) link;
reactorSender.dispose(errorCondition);
} else {
link.dispose();
}
subscription.dispose();
}
}
} | class ReactorSession implements AmqpSession {
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final ConcurrentMap<String, LinkSubscription<AmqpSendLink>> openSendLinks = new ConcurrentHashMap<>();
private final ConcurrentMap<String, LinkSubscription<AmqpReceiveLink>> openReceiveLinks = new ConcurrentHashMap<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final ClientLogger logger = new ClientLogger(ReactorSession.class);
private final ReplayProcessor<AmqpEndpointState> endpointStates;
private final Session session;
private final SessionHandler sessionHandler;
private final String sessionName;
private final ReactorProvider provider;
private final TokenManagerProvider tokenManagerProvider;
private final MessageSerializer messageSerializer;
private final String activeTimeoutMessage;
private final AmqpRetryOptions retryOptions;
private final ReactorHandlerProvider handlerProvider;
private final Mono<ClaimsBasedSecurityNode> cbsNodeSupplier;
private final AtomicReference<TransactionCoordinator> transactionCoordinator = new AtomicReference<>();
/**
* Creates a new AMQP session using proton-j.
*
* @param session Proton-j session for this AMQP session.
* @param sessionHandler Handler for events that occur in the session.
* @param sessionName Name of the session.
* @param provider Provides reactor instances for messages to sent with.
* @param handlerProvider Providers reactor handlers for listening to proton-j reactor events.
* @param cbsNodeSupplier Mono that returns a reference to the {@link ClaimsBasedSecurityNode}.
* @param tokenManagerProvider Provides {@link TokenManager} that authorizes the client when performing
* operations on the message broker.
* @param retryOptions for the session operations.
*/
public ReactorSession(Session session, SessionHandler sessionHandler, String sessionName, ReactorProvider provider,
ReactorHandlerProvider handlerProvider, Mono<ClaimsBasedSecurityNode> cbsNodeSupplier,
TokenManagerProvider tokenManagerProvider, MessageSerializer messageSerializer,
AmqpRetryOptions retryOptions) {
this.session = session;
this.sessionHandler = sessionHandler;
this.handlerProvider = handlerProvider;
this.sessionName = sessionName;
this.provider = provider;
this.cbsNodeSupplier = cbsNodeSupplier;
this.tokenManagerProvider = tokenManagerProvider;
this.messageSerializer = messageSerializer;
this.retryOptions = retryOptions;
this.activeTimeoutMessage = String.format(
"ReactorSession connectionId[%s], session[%s]: Retries exhausted waiting for ACTIVE endpoint state.",
sessionHandler.getConnectionId(), sessionName);
this.endpointStates = sessionHandler.getEndpointStates()
.map(state -> {
logger.verbose("connectionId[{}], sessionName[{}], state[{}]", sessionHandler.getConnectionId(),
sessionName, state);
return AmqpEndpointStateUtil.getConnectionState(state);
})
.subscribeWith(ReplayProcessor.cacheLastOrDefault(AmqpEndpointState.UNINITIALIZED));
session.open();
}
Session session() {
return this.session;
}
@Override
public Flux<AmqpEndpointState> getEndpointStates() {
return endpointStates;
}
@Override
public boolean isDisposed() {
return isDisposed.get();
}
/**
* {@inheritDoc}
*/
@Override
public void dispose() {
dispose(null);
}
/**
* {@inheritDoc}
*/
@Override
public String getSessionName() {
return sessionName;
}
/**
* {@inheritDoc}
*/
@Override
public Duration getOperationTimeout() {
return retryOptions.getTryTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpTransaction> createTransaction() {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.declare());
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> commitTransaction(AmqpTransaction transaction) {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.discharge(transaction, true));
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> rollbackTransaction(AmqpTransaction transaction) {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.discharge(transaction, false));
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry) {
return createProducer(linkName, entityPath, timeout, retry, null);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpLink> createConsumer(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry) {
return createConsumer(linkName, entityPath, timeout, retry, null, null, null,
SenderSettleMode.UNSETTLED, ReceiverSettleMode.SECOND)
.cast(AmqpLink.class);
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeLink(String linkName) {
return removeLink(openSendLinks, linkName) || removeLink(openReceiveLinks, linkName);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpTransactionCoordinator> getOrCreateTransactionCoordinator() {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create coordinator send link '%s' from a closed session.", TRANSACTION_LINK_NAME))));
}
final TransactionCoordinator existing = transactionCoordinator.get();
if (existing != null) {
logger.verbose("Coordinator[{}]: Returning existing transaction coordinator.", TRANSACTION_LINK_NAME);
return Mono.just(existing);
}
return createProducer(TRANSACTION_LINK_NAME, TRANSACTION_LINK_NAME, new Coordinator(), retryOptions, null,
false)
.map(link -> {
final TransactionCoordinator newCoordinator = new TransactionCoordinator(link, messageSerializer);
if (transactionCoordinator.compareAndSet(null, newCoordinator)) {
return newCoordinator;
} else {
return transactionCoordinator.get();
}
});
}
/**
* Creates an {@link AmqpReceiveLink} that has AMQP specific capabilities set.
*
* Filters can be applied to the source when receiving to inform the source to filter the items sent to the
* consumer. See
* <a href="http:
* Messages</a> and <a href="https:
*
* @param linkName Name of the receive link.
* @param entityPath Address in the message broker for the link.
* @param timeout Operation timeout when creating the link.
* @param retry Retry policy to apply when link creation times out.
* @param sourceFilters Add any filters to the source when creating the receive link.
* @param receiverProperties Any properties to associate with the receive link when attaching to message
* broker.
* @param receiverDesiredCapabilities Capabilities that the receiver link supports.
* @param senderSettleMode Amqp {@link SenderSettleMode} mode for receiver.
* @param receiverSettleMode Amqp {@link ReceiverSettleMode} mode for receiver.
*
* @return A new instance of an {@link AmqpReceiveLink} with the correct properties set.
*/
protected Mono<AmqpReceiveLink> createConsumer(String linkName, String entityPath, Duration timeout,
AmqpRetryPolicy retry, Map<Symbol, Object> sourceFilters, Map<Symbol, Object> receiverProperties,
Symbol[] receiverDesiredCapabilities, SenderSettleMode senderSettleMode,
ReceiverSettleMode receiverSettleMode) {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create receive link '%s' from a closed session. entityPath[%s]", linkName, entityPath))));
}
final LinkSubscription<AmqpReceiveLink> existingLink = openReceiveLinks.get(linkName);
if (existingLink != null) {
logger.info("linkName[{}] entityPath[{}]: Returning existing receive link.", linkName, entityPath);
return Mono.just(existingLink.getLink());
}
final TokenManager tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath);
return Mono.when(onActiveEndpoint(), tokenManager.authorize()).then(Mono.create(sink -> {
try {
provider.getReactorDispatcher().invoke(() -> {
final LinkSubscription<AmqpReceiveLink> computed = openReceiveLinks.compute(linkName,
(linkNameKey, existing) -> {
if (existing != null) {
logger.info("linkName[{}]: Another receive link exists. Disposing of new one.",
linkName);
tokenManager.close();
return existing;
}
logger.info("Creating a new receiver link with linkName {}", linkName);
return getSubscription(linkNameKey, entityPath, sourceFilters, receiverProperties,
receiverDesiredCapabilities, senderSettleMode, receiverSettleMode, tokenManager);
});
sink.success(computed.getLink());
});
} catch (IOException e) {
sink.error(e);
}
}));
}
/**
* Given the entity path, associated receiver and link handler, creates the receive link instance.
*/
protected ReactorReceiver createConsumer(String entityPath, Receiver receiver,
ReceiveLinkHandler receiveLinkHandler, TokenManager tokenManager, ReactorProvider reactorProvider) {
return new ReactorReceiver(entityPath, receiver, receiveLinkHandler, tokenManager,
reactorProvider.getReactorDispatcher());
}
/**
* Creates an {@link AmqpLink} that has AMQP specific capabilities set.
*
* @param linkName Name of the receive link.
* @param entityPath Address in the message broker for the link.
* @param linkProperties The properties needed to be set on the link.
* @param timeout Operation timeout when creating the link.
* @param retry Retry policy to apply when link creation times out.
*
* @return A new instance of an {@link AmqpLink} with the correct properties set.
*/
protected Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout,
AmqpRetryPolicy retry, Map<Symbol, Object> linkProperties) {
final Target target = new Target();
target.setAddress(entityPath);
final AmqpRetryOptions options = retry != null
? new AmqpRetryOptions(retry.getRetryOptions())
: new AmqpRetryOptions();
if (timeout != null) {
options.setTryTimeout(timeout);
}
return createProducer(linkName, entityPath, target, options, linkProperties, true)
.cast(AmqpLink.class);
}
private Mono<AmqpSendLink> createProducer(String linkName, String entityPath,
org.apache.qpid.proton.amqp.transport.Target target, AmqpRetryOptions options,
Map<Symbol, Object> linkProperties, boolean requiresAuthorization) {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create send link '%s' from a closed session. entityPath[%s]", linkName, entityPath))));
}
final LinkSubscription<AmqpSendLink> existing = openSendLinks.get(linkName);
if (existing != null) {
logger.verbose("linkName[{}]: Returning existing send link.", linkName);
return Mono.just(existing.getLink());
}
final TokenManager tokenManager;
final Mono<Long> authorize;
if (requiresAuthorization) {
tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath);
authorize = tokenManager.authorize();
} else {
tokenManager = null;
authorize = Mono.empty();
}
return Mono.when(onActiveEndpoint(), authorize).then(Mono.create(sink -> {
try {
provider.getReactorDispatcher().invoke(() -> {
final LinkSubscription<AmqpSendLink> computed = openSendLinks.compute(linkName,
(linkNameKey, existingLink) -> {
if (existingLink != null) {
logger.info("linkName[{}]: Another send link exists. Disposing of new one.",
linkName);
if (tokenManager != null) {
tokenManager.close();
}
return existingLink;
}
logger.info("Creating a new sender link with linkName {}", linkName);
return getSubscription(linkName, entityPath, target, linkProperties, options,
tokenManager);
});
sink.success(computed.getLink());
});
} catch (IOException e) {
sink.error(e);
}
}));
}
/**
* NOTE: Ensure this is invoked using the reactor dispatcher because proton-j is not thread-safe.
*/
private LinkSubscription<AmqpSendLink> getSubscription(String linkName, String entityPath,
org.apache.qpid.proton.amqp.transport.Target target, Map<Symbol, Object> linkProperties,
AmqpRetryOptions options, TokenManager tokenManager) {
final Sender sender = session.sender(linkName);
sender.setTarget(target);
final Source source = new Source();
sender.setSource(source);
sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
if (linkProperties != null && linkProperties.size() > 0) {
sender.setProperties(linkProperties);
}
final SendLinkHandler sendLinkHandler = handlerProvider.createSendLinkHandler(
sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath);
BaseHandler.setHandler(sender, sendLinkHandler);
sender.open();
final ReactorSender reactorSender = new ReactorSender(entityPath, sender, sendLinkHandler, provider,
tokenManager, messageSerializer, options);
final Disposable subscription = reactorSender.getEndpointStates().subscribe(state -> {
}, error -> {
logger.info("linkName[{}]: Error occurred. Removing and disposing send link.",
linkName, error);
removeLink(openSendLinks, linkName);
}, () -> {
logger.info("linkName[{}]: Complete. Removing and disposing send link.", linkName);
removeLink(openSendLinks, linkName);
});
return new LinkSubscription<>(reactorSender, subscription);
}
/**
* NOTE: Ensure this is invoked using the reactor dispatcher because proton-j is not thread-safe.
*/
private LinkSubscription<AmqpReceiveLink> getSubscription(String linkName, String entityPath,
Map<Symbol, Object> sourceFilters, Map<Symbol, Object> receiverProperties,
Symbol[] receiverDesiredCapabilities, SenderSettleMode senderSettleMode, ReceiverSettleMode receiverSettleMode,
TokenManager tokenManager) {
final Receiver receiver = session.receiver(linkName);
final Source source = new Source();
source.setAddress(entityPath);
if (sourceFilters != null && sourceFilters.size() > 0) {
source.setFilter(sourceFilters);
}
receiver.setSource(source);
final Target target = new Target();
receiver.setTarget(target);
receiver.setSenderSettleMode(senderSettleMode);
receiver.setReceiverSettleMode(receiverSettleMode);
if (receiverProperties != null && !receiverProperties.isEmpty()) {
receiver.setProperties(receiverProperties);
}
if (receiverDesiredCapabilities != null && receiverDesiredCapabilities.length > 0) {
receiver.setDesiredCapabilities(receiverDesiredCapabilities);
}
final ReceiveLinkHandler receiveLinkHandler = handlerProvider.createReceiveLinkHandler(
sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath);
BaseHandler.setHandler(receiver, receiveLinkHandler);
receiver.open();
final ReactorReceiver reactorReceiver = createConsumer(entityPath, receiver, receiveLinkHandler,
tokenManager, provider);
final Disposable subscription = reactorReceiver.getEndpointStates().subscribe(state -> {
}, error -> {
logger.info(
"linkName[{}] entityPath[{}]: Error occurred. Removing receive link.",
linkName, entityPath, error);
removeLink(openReceiveLinks, linkName);
}, () -> {
logger.info("linkName[{}] entityPath[{}]: Complete. Removing receive link.",
linkName, entityPath);
removeLink(openReceiveLinks, linkName);
});
return new LinkSubscription<>(reactorReceiver, subscription);
}
/**
* Asynchronously waits for the session's active endpoint state.
*
* @return A mono that completes when the session is active.
*/
private Mono<Void> onActiveEndpoint() {
return RetryUtil.withRetry(getEndpointStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE),
retryOptions, activeTimeoutMessage)
.then();
}
private <T extends AmqpLink> boolean removeLink(ConcurrentMap<String, LinkSubscription<T>> openLinks, String key) {
if (key == null) {
return false;
}
final LinkSubscription<T> removed = openLinks.remove(key);
if (removed != null) {
removed.dispose(null);
}
return removed != null;
}
private static final class LinkSubscription<T extends AmqpLink> {
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final T link;
private final Disposable subscription;
private LinkSubscription(T link, Disposable subscription) {
this.link = link;
this.subscription = subscription;
}
public T getLink() {
return link;
}
void dispose(ErrorCondition errorCondition) {
if (isDisposed.getAndSet(true)) {
return;
}
if (link instanceof ReactorReceiver) {
final ReactorReceiver reactorReceiver = (ReactorReceiver) link;
reactorReceiver.dispose(errorCondition);
} else if (link instanceof ReactorSender) {
final ReactorSender reactorSender = (ReactorSender) link;
reactorSender.dispose(errorCondition);
} else {
link.dispose();
}
subscription.dispose();
}
}
} |
left over, removing. | void dispose(ErrorCondition errorCondition) {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("connectionId[{}], sessionId[{}], errorCondition[{}]: Disposing of session.",
sessionHandler.getConnectionId(), sessionName, errorCondition != null ? errorCondition : NOT_APPLICABLE);
if (session.getLocalState() != EndpointState.CLOSED) {
session.close();
if (session.getCondition() == null) {
session.setCondition(errorCondition);
}
}
openReceiveLinks.forEach((key, link) -> link.dispose(errorCondition));
openSendLinks.forEach((key, link) -> link.dispose(errorCondition));
if (transactionCoordinator.get() != null) {
transactionCoordinator.get();
}
} | } | void dispose(ErrorCondition errorCondition) {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("connectionId[{}], sessionId[{}], errorCondition[{}]: Disposing of session.",
sessionHandler.getConnectionId(), sessionName, errorCondition != null ? errorCondition : NOT_APPLICABLE);
if (session.getLocalState() != EndpointState.CLOSED) {
session.close();
if (session.getCondition() == null) {
session.setCondition(errorCondition);
}
}
openReceiveLinks.forEach((key, link) -> link.dispose(errorCondition));
openSendLinks.forEach((key, link) -> link.dispose(errorCondition));
} | class ReactorSession implements AmqpSession {
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final ConcurrentMap<String, LinkSubscription<AmqpSendLink>> openSendLinks = new ConcurrentHashMap<>();
private final ConcurrentMap<String, LinkSubscription<AmqpReceiveLink>> openReceiveLinks = new ConcurrentHashMap<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final ClientLogger logger = new ClientLogger(ReactorSession.class);
private final ReplayProcessor<AmqpEndpointState> endpointStates;
private final Session session;
private final SessionHandler sessionHandler;
private final String sessionName;
private final ReactorProvider provider;
private final TokenManagerProvider tokenManagerProvider;
private final MessageSerializer messageSerializer;
private final String activeTimeoutMessage;
private final AmqpRetryOptions retryOptions;
private final ReactorHandlerProvider handlerProvider;
private final Mono<ClaimsBasedSecurityNode> cbsNodeSupplier;
private final AtomicReference<TransactionCoordinator> transactionCoordinator = new AtomicReference<>();
/**
* Creates a new AMQP session using proton-j.
*
* @param session Proton-j session for this AMQP session.
* @param sessionHandler Handler for events that occur in the session.
* @param sessionName Name of the session.
* @param provider Provides reactor instances for messages to sent with.
* @param handlerProvider Providers reactor handlers for listening to proton-j reactor events.
* @param cbsNodeSupplier Mono that returns a reference to the {@link ClaimsBasedSecurityNode}.
* @param tokenManagerProvider Provides {@link TokenManager} that authorizes the client when performing
* operations on the message broker.
* @param retryOptions for the session operations.
*/
public ReactorSession(Session session, SessionHandler sessionHandler, String sessionName, ReactorProvider provider,
ReactorHandlerProvider handlerProvider, Mono<ClaimsBasedSecurityNode> cbsNodeSupplier,
TokenManagerProvider tokenManagerProvider, MessageSerializer messageSerializer,
AmqpRetryOptions retryOptions) {
this.session = session;
this.sessionHandler = sessionHandler;
this.handlerProvider = handlerProvider;
this.sessionName = sessionName;
this.provider = provider;
this.cbsNodeSupplier = cbsNodeSupplier;
this.tokenManagerProvider = tokenManagerProvider;
this.messageSerializer = messageSerializer;
this.retryOptions = retryOptions;
this.activeTimeoutMessage = String.format(
"ReactorSession connectionId[%s], session[%s]: Retries exhausted waiting for ACTIVE endpoint state.",
sessionHandler.getConnectionId(), sessionName);
this.endpointStates = sessionHandler.getEndpointStates()
.map(state -> {
logger.verbose("connectionId[{}], sessionName[{}], state[{}]", sessionHandler.getConnectionId(),
sessionName, state);
return AmqpEndpointStateUtil.getConnectionState(state);
})
.subscribeWith(ReplayProcessor.cacheLastOrDefault(AmqpEndpointState.UNINITIALIZED));
session.open();
}
Session session() {
return this.session;
}
@Override
public Flux<AmqpEndpointState> getEndpointStates() {
return endpointStates;
}
@Override
public boolean isDisposed() {
return isDisposed.get();
}
/**
* {@inheritDoc}
*/
@Override
public void dispose() {
dispose(null);
}
/**
* {@inheritDoc}
*/
@Override
public String getSessionName() {
return sessionName;
}
/**
* {@inheritDoc}
*/
@Override
public Duration getOperationTimeout() {
return retryOptions.getTryTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpTransaction> createTransaction() {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.declare());
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> commitTransaction(AmqpTransaction transaction) {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.discharge(transaction, true));
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> rollbackTransaction(AmqpTransaction transaction) {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.discharge(transaction, false));
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry) {
return createProducer(linkName, entityPath, timeout, retry, null);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpLink> createConsumer(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry) {
return createConsumer(linkName, entityPath, timeout, retry, null, null, null,
SenderSettleMode.UNSETTLED, ReceiverSettleMode.SECOND)
.cast(AmqpLink.class);
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeLink(String linkName) {
return removeLink(openSendLinks, linkName) || removeLink(openReceiveLinks, linkName);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpTransactionCoordinator> getOrCreateTransactionCoordinator() {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create coordinator send link '%s' from a closed session.", TRANSACTION_LINK_NAME))));
}
final TransactionCoordinator existing = transactionCoordinator.get();
if (existing != null) {
logger.verbose("Coordinator[{}]: Returning existing transaction coordinator.", TRANSACTION_LINK_NAME);
return Mono.just(existing);
}
return createProducer(TRANSACTION_LINK_NAME, TRANSACTION_LINK_NAME, new Coordinator(), retryOptions, null,
false)
.map(link -> {
final TransactionCoordinator newCoordinator = new TransactionCoordinator(link, messageSerializer);
if (transactionCoordinator.compareAndSet(null, newCoordinator)) {
return newCoordinator;
} else {
return transactionCoordinator.get();
}
});
}
/**
* Creates an {@link AmqpReceiveLink} that has AMQP specific capabilities set.
*
* Filters can be applied to the source when receiving to inform the source to filter the items sent to the
* consumer. See
* <a href="http:
* Messages</a> and <a href="https:
*
* @param linkName Name of the receive link.
* @param entityPath Address in the message broker for the link.
* @param timeout Operation timeout when creating the link.
* @param retry Retry policy to apply when link creation times out.
* @param sourceFilters Add any filters to the source when creating the receive link.
* @param receiverProperties Any properties to associate with the receive link when attaching to message
* broker.
* @param receiverDesiredCapabilities Capabilities that the receiver link supports.
* @param senderSettleMode Amqp {@link SenderSettleMode} mode for receiver.
* @param receiverSettleMode Amqp {@link ReceiverSettleMode} mode for receiver.
*
* @return A new instance of an {@link AmqpReceiveLink} with the correct properties set.
*/
protected Mono<AmqpReceiveLink> createConsumer(String linkName, String entityPath, Duration timeout,
AmqpRetryPolicy retry, Map<Symbol, Object> sourceFilters, Map<Symbol, Object> receiverProperties,
Symbol[] receiverDesiredCapabilities, SenderSettleMode senderSettleMode,
ReceiverSettleMode receiverSettleMode) {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create receive link '%s' from a closed session. entityPath[%s]", linkName, entityPath))));
}
final LinkSubscription<AmqpReceiveLink> existingLink = openReceiveLinks.get(linkName);
if (existingLink != null) {
logger.info("linkName[{}] entityPath[{}]: Returning existing receive link.", linkName, entityPath);
return Mono.just(existingLink.getLink());
}
final TokenManager tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath);
return Mono.when(onActiveEndpoint(), tokenManager.authorize()).then(Mono.create(sink -> {
try {
provider.getReactorDispatcher().invoke(() -> {
final LinkSubscription<AmqpReceiveLink> computed = openReceiveLinks.compute(linkName,
(linkNameKey, existing) -> {
if (existing != null) {
logger.info("linkName[{}]: Another receive link exists. Disposing of new one.",
linkName);
tokenManager.close();
return existing;
}
logger.info("Creating a new receiver link with linkName {}", linkName);
return getSubscription(linkNameKey, entityPath, sourceFilters, receiverProperties,
receiverDesiredCapabilities, senderSettleMode, receiverSettleMode, tokenManager);
});
sink.success(computed.getLink());
});
} catch (IOException e) {
sink.error(e);
}
}));
}
/**
* Given the entity path, associated receiver and link handler, creates the receive link instance.
*/
protected ReactorReceiver createConsumer(String entityPath, Receiver receiver,
ReceiveLinkHandler receiveLinkHandler, TokenManager tokenManager, ReactorProvider reactorProvider) {
return new ReactorReceiver(entityPath, receiver, receiveLinkHandler, tokenManager,
reactorProvider.getReactorDispatcher());
}
/**
* Creates an {@link AmqpLink} that has AMQP specific capabilities set.
*
* @param linkName Name of the receive link.
* @param entityPath Address in the message broker for the link.
* @param linkProperties The properties needed to be set on the link.
* @param timeout Operation timeout when creating the link.
* @param retry Retry policy to apply when link creation times out.
*
* @return A new instance of an {@link AmqpLink} with the correct properties set.
*/
protected Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout,
AmqpRetryPolicy retry, Map<Symbol, Object> linkProperties) {
final Target target = new Target();
target.setAddress(entityPath);
final AmqpRetryOptions options = retry != null
? new AmqpRetryOptions(retry.getRetryOptions())
: new AmqpRetryOptions();
if (timeout != null) {
options.setTryTimeout(timeout);
}
return createProducer(linkName, entityPath, target, options, linkProperties, true)
.cast(AmqpLink.class);
}
private Mono<AmqpSendLink> createProducer(String linkName, String entityPath,
org.apache.qpid.proton.amqp.transport.Target target, AmqpRetryOptions options,
Map<Symbol, Object> linkProperties, boolean requiresAuthorization) {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create send link '%s' from a closed session. entityPath[%s]", linkName, entityPath))));
}
final LinkSubscription<AmqpSendLink> existing = openSendLinks.get(linkName);
if (existing != null) {
logger.verbose("linkName[{}]: Returning existing send link.", linkName);
return Mono.just(existing.getLink());
}
final TokenManager tokenManager;
final Mono<Long> authorize;
if (requiresAuthorization) {
tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath);
authorize = tokenManager.authorize();
} else {
tokenManager = null;
authorize = Mono.empty();
}
return Mono.when(onActiveEndpoint(), authorize).then(Mono.create(sink -> {
try {
provider.getReactorDispatcher().invoke(() -> {
final LinkSubscription<AmqpSendLink> computed = openSendLinks.compute(linkName,
(linkNameKey, existingLink) -> {
if (existingLink != null) {
logger.info("linkName[{}]: Another send link exists. Disposing of new one.",
linkName);
if (tokenManager != null) {
tokenManager.close();
}
return existingLink;
}
logger.info("Creating a new sender link with linkName {}", linkName);
return getSubscription(linkName, entityPath, target, linkProperties, options,
tokenManager);
});
sink.success(computed.getLink());
});
} catch (IOException e) {
sink.error(e);
}
}));
}
/**
* NOTE: Ensure this is invoked using the reactor dispatcher because proton-j is not thread-safe.
*/
private LinkSubscription<AmqpSendLink> getSubscription(String linkName, String entityPath,
org.apache.qpid.proton.amqp.transport.Target target, Map<Symbol, Object> linkProperties,
AmqpRetryOptions options, TokenManager tokenManager) {
final Sender sender = session.sender(linkName);
sender.setTarget(target);
final Source source = new Source();
sender.setSource(source);
sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
if (linkProperties != null && linkProperties.size() > 0) {
sender.setProperties(linkProperties);
}
final SendLinkHandler sendLinkHandler = handlerProvider.createSendLinkHandler(
sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath);
BaseHandler.setHandler(sender, sendLinkHandler);
sender.open();
final ReactorSender reactorSender = new ReactorSender(entityPath, sender, sendLinkHandler, provider,
tokenManager, messageSerializer, options);
final Disposable subscription = reactorSender.getEndpointStates().subscribe(state -> {
}, error -> {
logger.info("linkName[{}]: Error occurred. Removing and disposing send link.",
linkName, error);
removeLink(openSendLinks, linkName);
}, () -> {
logger.info("linkName[{}]: Complete. Removing and disposing send link.", linkName);
removeLink(openSendLinks, linkName);
});
return new LinkSubscription<>(reactorSender, subscription);
}
/**
* NOTE: Ensure this is invoked using the reactor dispatcher because proton-j is not thread-safe.
*/
private LinkSubscription<AmqpReceiveLink> getSubscription(String linkName, String entityPath,
Map<Symbol, Object> sourceFilters, Map<Symbol, Object> receiverProperties,
Symbol[] receiverDesiredCapabilities, SenderSettleMode senderSettleMode, ReceiverSettleMode receiverSettleMode,
TokenManager tokenManager) {
final Receiver receiver = session.receiver(linkName);
final Source source = new Source();
source.setAddress(entityPath);
if (sourceFilters != null && sourceFilters.size() > 0) {
source.setFilter(sourceFilters);
}
receiver.setSource(source);
final Target target = new Target();
receiver.setTarget(target);
receiver.setSenderSettleMode(senderSettleMode);
receiver.setReceiverSettleMode(receiverSettleMode);
if (receiverProperties != null && !receiverProperties.isEmpty()) {
receiver.setProperties(receiverProperties);
}
if (receiverDesiredCapabilities != null && receiverDesiredCapabilities.length > 0) {
receiver.setDesiredCapabilities(receiverDesiredCapabilities);
}
final ReceiveLinkHandler receiveLinkHandler = handlerProvider.createReceiveLinkHandler(
sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath);
BaseHandler.setHandler(receiver, receiveLinkHandler);
receiver.open();
final ReactorReceiver reactorReceiver = createConsumer(entityPath, receiver, receiveLinkHandler,
tokenManager, provider);
final Disposable subscription = reactorReceiver.getEndpointStates().subscribe(state -> {
}, error -> {
logger.info(
"linkName[{}] entityPath[{}]: Error occurred. Removing receive link.",
linkName, entityPath, error);
removeLink(openReceiveLinks, linkName);
}, () -> {
logger.info("linkName[{}] entityPath[{}]: Complete. Removing receive link.",
linkName, entityPath);
removeLink(openReceiveLinks, linkName);
});
return new LinkSubscription<>(reactorReceiver, subscription);
}
/**
* Asynchronously waits for the session's active endpoint state.
*
* @return A mono that completes when the session is active.
*/
private Mono<Void> onActiveEndpoint() {
return RetryUtil.withRetry(getEndpointStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE),
retryOptions, activeTimeoutMessage)
.then();
}
private <T extends AmqpLink> boolean removeLink(ConcurrentMap<String, LinkSubscription<T>> openLinks, String key) {
if (key == null) {
return false;
}
final LinkSubscription<T> removed = openLinks.remove(key);
if (removed != null) {
removed.dispose(null);
}
return removed != null;
}
private static final class LinkSubscription<T extends AmqpLink> {
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final T link;
private final Disposable subscription;
private LinkSubscription(T link, Disposable subscription) {
this.link = link;
this.subscription = subscription;
}
public T getLink() {
return link;
}
void dispose(ErrorCondition errorCondition) {
if (isDisposed.getAndSet(true)) {
return;
}
if (link instanceof ReactorReceiver) {
final ReactorReceiver reactorReceiver = (ReactorReceiver) link;
reactorReceiver.dispose(errorCondition);
} else if (link instanceof ReactorSender) {
final ReactorSender reactorSender = (ReactorSender) link;
reactorSender.dispose(errorCondition);
} else {
link.dispose();
}
subscription.dispose();
}
}
} | class ReactorSession implements AmqpSession {
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final ConcurrentMap<String, LinkSubscription<AmqpSendLink>> openSendLinks = new ConcurrentHashMap<>();
private final ConcurrentMap<String, LinkSubscription<AmqpReceiveLink>> openReceiveLinks = new ConcurrentHashMap<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final ClientLogger logger = new ClientLogger(ReactorSession.class);
private final ReplayProcessor<AmqpEndpointState> endpointStates;
private final Session session;
private final SessionHandler sessionHandler;
private final String sessionName;
private final ReactorProvider provider;
private final TokenManagerProvider tokenManagerProvider;
private final MessageSerializer messageSerializer;
private final String activeTimeoutMessage;
private final AmqpRetryOptions retryOptions;
private final ReactorHandlerProvider handlerProvider;
private final Mono<ClaimsBasedSecurityNode> cbsNodeSupplier;
private final AtomicReference<TransactionCoordinator> transactionCoordinator = new AtomicReference<>();
/**
* Creates a new AMQP session using proton-j.
*
* @param session Proton-j session for this AMQP session.
* @param sessionHandler Handler for events that occur in the session.
* @param sessionName Name of the session.
* @param provider Provides reactor instances for messages to sent with.
* @param handlerProvider Providers reactor handlers for listening to proton-j reactor events.
* @param cbsNodeSupplier Mono that returns a reference to the {@link ClaimsBasedSecurityNode}.
* @param tokenManagerProvider Provides {@link TokenManager} that authorizes the client when performing
* operations on the message broker.
* @param retryOptions for the session operations.
*/
public ReactorSession(Session session, SessionHandler sessionHandler, String sessionName, ReactorProvider provider,
ReactorHandlerProvider handlerProvider, Mono<ClaimsBasedSecurityNode> cbsNodeSupplier,
TokenManagerProvider tokenManagerProvider, MessageSerializer messageSerializer,
AmqpRetryOptions retryOptions) {
this.session = session;
this.sessionHandler = sessionHandler;
this.handlerProvider = handlerProvider;
this.sessionName = sessionName;
this.provider = provider;
this.cbsNodeSupplier = cbsNodeSupplier;
this.tokenManagerProvider = tokenManagerProvider;
this.messageSerializer = messageSerializer;
this.retryOptions = retryOptions;
this.activeTimeoutMessage = String.format(
"ReactorSession connectionId[%s], session[%s]: Retries exhausted waiting for ACTIVE endpoint state.",
sessionHandler.getConnectionId(), sessionName);
this.endpointStates = sessionHandler.getEndpointStates()
.map(state -> {
logger.verbose("connectionId[{}], sessionName[{}], state[{}]", sessionHandler.getConnectionId(),
sessionName, state);
return AmqpEndpointStateUtil.getConnectionState(state);
})
.subscribeWith(ReplayProcessor.cacheLastOrDefault(AmqpEndpointState.UNINITIALIZED));
session.open();
}
Session session() {
return this.session;
}
@Override
public Flux<AmqpEndpointState> getEndpointStates() {
return endpointStates;
}
@Override
public boolean isDisposed() {
return isDisposed.get();
}
/**
* {@inheritDoc}
*/
@Override
public void dispose() {
dispose(null);
}
/**
* {@inheritDoc}
*/
@Override
public String getSessionName() {
return sessionName;
}
/**
* {@inheritDoc}
*/
@Override
public Duration getOperationTimeout() {
return retryOptions.getTryTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpTransaction> createTransaction() {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.declare());
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> commitTransaction(AmqpTransaction transaction) {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.discharge(transaction, true));
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> rollbackTransaction(AmqpTransaction transaction) {
return getOrCreateTransactionCoordinator()
.flatMap(coordinator -> coordinator.discharge(transaction, false));
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry) {
return createProducer(linkName, entityPath, timeout, retry, null);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpLink> createConsumer(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry) {
return createConsumer(linkName, entityPath, timeout, retry, null, null, null,
SenderSettleMode.UNSETTLED, ReceiverSettleMode.SECOND)
.cast(AmqpLink.class);
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeLink(String linkName) {
return removeLink(openSendLinks, linkName) || removeLink(openReceiveLinks, linkName);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<AmqpTransactionCoordinator> getOrCreateTransactionCoordinator() {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create coordinator send link '%s' from a closed session.", TRANSACTION_LINK_NAME))));
}
final TransactionCoordinator existing = transactionCoordinator.get();
if (existing != null) {
logger.verbose("Coordinator[{}]: Returning existing transaction coordinator.", TRANSACTION_LINK_NAME);
return Mono.just(existing);
}
return createProducer(TRANSACTION_LINK_NAME, TRANSACTION_LINK_NAME, new Coordinator(), retryOptions, null,
false)
.map(link -> {
final TransactionCoordinator newCoordinator = new TransactionCoordinator(link, messageSerializer);
if (transactionCoordinator.compareAndSet(null, newCoordinator)) {
return newCoordinator;
} else {
return transactionCoordinator.get();
}
});
}
/**
* Creates an {@link AmqpReceiveLink} that has AMQP specific capabilities set.
*
* Filters can be applied to the source when receiving to inform the source to filter the items sent to the
* consumer. See
* <a href="http:
* Messages</a> and <a href="https:
*
* @param linkName Name of the receive link.
* @param entityPath Address in the message broker for the link.
* @param timeout Operation timeout when creating the link.
* @param retry Retry policy to apply when link creation times out.
* @param sourceFilters Add any filters to the source when creating the receive link.
* @param receiverProperties Any properties to associate with the receive link when attaching to message
* broker.
* @param receiverDesiredCapabilities Capabilities that the receiver link supports.
* @param senderSettleMode Amqp {@link SenderSettleMode} mode for receiver.
* @param receiverSettleMode Amqp {@link ReceiverSettleMode} mode for receiver.
*
* @return A new instance of an {@link AmqpReceiveLink} with the correct properties set.
*/
protected Mono<AmqpReceiveLink> createConsumer(String linkName, String entityPath, Duration timeout,
AmqpRetryPolicy retry, Map<Symbol, Object> sourceFilters, Map<Symbol, Object> receiverProperties,
Symbol[] receiverDesiredCapabilities, SenderSettleMode senderSettleMode,
ReceiverSettleMode receiverSettleMode) {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create receive link '%s' from a closed session. entityPath[%s]", linkName, entityPath))));
}
final LinkSubscription<AmqpReceiveLink> existingLink = openReceiveLinks.get(linkName);
if (existingLink != null) {
logger.info("linkName[{}] entityPath[{}]: Returning existing receive link.", linkName, entityPath);
return Mono.just(existingLink.getLink());
}
final TokenManager tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath);
return Mono.when(onActiveEndpoint(), tokenManager.authorize()).then(Mono.create(sink -> {
try {
provider.getReactorDispatcher().invoke(() -> {
final LinkSubscription<AmqpReceiveLink> computed = openReceiveLinks.compute(linkName,
(linkNameKey, existing) -> {
if (existing != null) {
logger.info("linkName[{}]: Another receive link exists. Disposing of new one.",
linkName);
tokenManager.close();
return existing;
}
logger.info("Creating a new receiver link with linkName {}", linkName);
return getSubscription(linkNameKey, entityPath, sourceFilters, receiverProperties,
receiverDesiredCapabilities, senderSettleMode, receiverSettleMode, tokenManager);
});
sink.success(computed.getLink());
});
} catch (IOException e) {
sink.error(e);
}
}));
}
/**
* Given the entity path, associated receiver and link handler, creates the receive link instance.
*/
protected ReactorReceiver createConsumer(String entityPath, Receiver receiver,
ReceiveLinkHandler receiveLinkHandler, TokenManager tokenManager, ReactorProvider reactorProvider) {
return new ReactorReceiver(entityPath, receiver, receiveLinkHandler, tokenManager,
reactorProvider.getReactorDispatcher());
}
/**
* Creates an {@link AmqpLink} that has AMQP specific capabilities set.
*
* @param linkName Name of the receive link.
* @param entityPath Address in the message broker for the link.
* @param linkProperties The properties needed to be set on the link.
* @param timeout Operation timeout when creating the link.
* @param retry Retry policy to apply when link creation times out.
*
* @return A new instance of an {@link AmqpLink} with the correct properties set.
*/
protected Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout,
AmqpRetryPolicy retry, Map<Symbol, Object> linkProperties) {
final Target target = new Target();
target.setAddress(entityPath);
final AmqpRetryOptions options = retry != null
? new AmqpRetryOptions(retry.getRetryOptions())
: new AmqpRetryOptions();
if (timeout != null) {
options.setTryTimeout(timeout);
}
return createProducer(linkName, entityPath, target, options, linkProperties, true)
.cast(AmqpLink.class);
}
private Mono<AmqpSendLink> createProducer(String linkName, String entityPath,
org.apache.qpid.proton.amqp.transport.Target target, AmqpRetryOptions options,
Map<Symbol, Object> linkProperties, boolean requiresAuthorization) {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot create send link '%s' from a closed session. entityPath[%s]", linkName, entityPath))));
}
final LinkSubscription<AmqpSendLink> existing = openSendLinks.get(linkName);
if (existing != null) {
logger.verbose("linkName[{}]: Returning existing send link.", linkName);
return Mono.just(existing.getLink());
}
final TokenManager tokenManager;
final Mono<Long> authorize;
if (requiresAuthorization) {
tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath);
authorize = tokenManager.authorize();
} else {
tokenManager = null;
authorize = Mono.empty();
}
return Mono.when(onActiveEndpoint(), authorize).then(Mono.create(sink -> {
try {
provider.getReactorDispatcher().invoke(() -> {
final LinkSubscription<AmqpSendLink> computed = openSendLinks.compute(linkName,
(linkNameKey, existingLink) -> {
if (existingLink != null) {
logger.info("linkName[{}]: Another send link exists. Disposing of new one.",
linkName);
if (tokenManager != null) {
tokenManager.close();
}
return existingLink;
}
logger.info("Creating a new sender link with linkName {}", linkName);
return getSubscription(linkName, entityPath, target, linkProperties, options,
tokenManager);
});
sink.success(computed.getLink());
});
} catch (IOException e) {
sink.error(e);
}
}));
}
/**
* NOTE: Ensure this is invoked using the reactor dispatcher because proton-j is not thread-safe.
*/
private LinkSubscription<AmqpSendLink> getSubscription(String linkName, String entityPath,
org.apache.qpid.proton.amqp.transport.Target target, Map<Symbol, Object> linkProperties,
AmqpRetryOptions options, TokenManager tokenManager) {
final Sender sender = session.sender(linkName);
sender.setTarget(target);
final Source source = new Source();
sender.setSource(source);
sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
if (linkProperties != null && linkProperties.size() > 0) {
sender.setProperties(linkProperties);
}
final SendLinkHandler sendLinkHandler = handlerProvider.createSendLinkHandler(
sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath);
BaseHandler.setHandler(sender, sendLinkHandler);
sender.open();
final ReactorSender reactorSender = new ReactorSender(entityPath, sender, sendLinkHandler, provider,
tokenManager, messageSerializer, options);
final Disposable subscription = reactorSender.getEndpointStates().subscribe(state -> {
}, error -> {
logger.info("linkName[{}]: Error occurred. Removing and disposing send link.",
linkName, error);
removeLink(openSendLinks, linkName);
}, () -> {
logger.info("linkName[{}]: Complete. Removing and disposing send link.", linkName);
removeLink(openSendLinks, linkName);
});
return new LinkSubscription<>(reactorSender, subscription);
}
/**
* NOTE: Ensure this is invoked using the reactor dispatcher because proton-j is not thread-safe.
*/
private LinkSubscription<AmqpReceiveLink> getSubscription(String linkName, String entityPath,
Map<Symbol, Object> sourceFilters, Map<Symbol, Object> receiverProperties,
Symbol[] receiverDesiredCapabilities, SenderSettleMode senderSettleMode, ReceiverSettleMode receiverSettleMode,
TokenManager tokenManager) {
final Receiver receiver = session.receiver(linkName);
final Source source = new Source();
source.setAddress(entityPath);
if (sourceFilters != null && sourceFilters.size() > 0) {
source.setFilter(sourceFilters);
}
receiver.setSource(source);
final Target target = new Target();
receiver.setTarget(target);
receiver.setSenderSettleMode(senderSettleMode);
receiver.setReceiverSettleMode(receiverSettleMode);
if (receiverProperties != null && !receiverProperties.isEmpty()) {
receiver.setProperties(receiverProperties);
}
if (receiverDesiredCapabilities != null && receiverDesiredCapabilities.length > 0) {
receiver.setDesiredCapabilities(receiverDesiredCapabilities);
}
final ReceiveLinkHandler receiveLinkHandler = handlerProvider.createReceiveLinkHandler(
sessionHandler.getConnectionId(), sessionHandler.getHostname(), linkName, entityPath);
BaseHandler.setHandler(receiver, receiveLinkHandler);
receiver.open();
final ReactorReceiver reactorReceiver = createConsumer(entityPath, receiver, receiveLinkHandler,
tokenManager, provider);
final Disposable subscription = reactorReceiver.getEndpointStates().subscribe(state -> {
}, error -> {
logger.info(
"linkName[{}] entityPath[{}]: Error occurred. Removing receive link.",
linkName, entityPath, error);
removeLink(openReceiveLinks, linkName);
}, () -> {
logger.info("linkName[{}] entityPath[{}]: Complete. Removing receive link.",
linkName, entityPath);
removeLink(openReceiveLinks, linkName);
});
return new LinkSubscription<>(reactorReceiver, subscription);
}
/**
* Asynchronously waits for the session's active endpoint state.
*
* @return A mono that completes when the session is active.
*/
private Mono<Void> onActiveEndpoint() {
return RetryUtil.withRetry(getEndpointStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE),
retryOptions, activeTimeoutMessage)
.then();
}
private <T extends AmqpLink> boolean removeLink(ConcurrentMap<String, LinkSubscription<T>> openLinks, String key) {
if (key == null) {
return false;
}
final LinkSubscription<T> removed = openLinks.remove(key);
if (removed != null) {
removed.dispose(null);
}
return removed != null;
}
private static final class LinkSubscription<T extends AmqpLink> {
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final T link;
private final Disposable subscription;
private LinkSubscription(T link, Disposable subscription) {
this.link = link;
this.subscription = subscription;
}
public T getLink() {
return link;
}
void dispose(ErrorCondition errorCondition) {
if (isDisposed.getAndSet(true)) {
return;
}
if (link instanceof ReactorReceiver) {
final ReactorReceiver reactorReceiver = (ReactorReceiver) link;
reactorReceiver.dispose(errorCondition);
} else if (link instanceof ReactorSender) {
final ReactorSender reactorSender = (ReactorSender) link;
reactorSender.dispose(errorCondition);
} else {
link.dispose();
}
subscription.dispose();
}
}
} |
was this intended? edit: I ask because it looks like we're passing content-type == PDF | public void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data),
dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
} | }), FORM_JPG); | public void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client
.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data),
dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
} | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient getFormRecognizerAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormRecognizerClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormTrainingClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
/**
* Verifies receipt data from a document using file data as source.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataNullData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
assertThrows(NullPointerException.class, () -> client.beginRecognizeReceipts(null, 0)
.getSyncPoller());
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeReceiptsOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data from a document using file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(
toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data from a document using PNG file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_PNG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_PNG);
}
/**
* Verifies receipt data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(
toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageReceiptData(syncPoller.getFinalResult());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verify that receipt recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies receipt data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize receipt from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceiptsFromUrl(invalidSourceUrl, new RecognizeReceiptsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies receipt data for a document using source as file url and include content when includeFieldElements is
* true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(
sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data for a document using source as PNG file url and include element references when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_PNG);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(
fileUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageReceiptData(syncPoller.getFinalResult());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
assertThrows(NullPointerException.class, () -> client.beginRecognizeContent(null, 0)
.getSyncPoller());
}
/**
* Verifies content type will be auto detected when using content/layout API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies blank form file is still a valid file to process
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, BLANK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verify that content recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContent(toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_ERROR_CODE, errorInformation.getErrorCode());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithSelectionMarks(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, SELECTION_MARK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Collections.singletonList("1")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(1, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPages(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Arrays.asList("1", "2")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(2, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPageRange(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Arrays.asList("1-2", "3")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(3, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentAppearance(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(TextStyleName.OTHER,
formPages.get(0).getLines().get(0).getAppearance().getStyle().getName());
}, FORM_JPG);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize a content from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies layout data for a pdf url
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, INVOICE_6_PDF);
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(invalidSourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner((formUrl) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(
formUrl, new RecognizeContentOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithSelectionMarksFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, SELECTION_MARK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeGermanContentFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode)
.setLanguage(FormRecognizerLanguage.DE))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
validateNetworkCallRecord("language", "de");
}, CONTENT_GERMAN_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentIncorrectLanguageFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(sourceUrl -> {
HttpResponseException exception
= assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode)
.setLanguage(FormRecognizerLanguage.fromString("language")))
.getSyncPoller());
assertEquals(((FormRecognizerErrorInformation) exception.getValue()).getErrorCode(), "NotSupportedLanguage");
}, CONTENT_GERMAN_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
/**
* Verifies custom form data for a JPG content type with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies custom form data for a blank PDF content type with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), BLANK_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id,
* excluding element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller()
.setPollInterval(durationTestMode);
syncPoller.waitForCompletion();
assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
syncPoller.getFinalResult().getModelId(), null, dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller());
}), INVOICE_6_PDF);
}
/**
* Verifies an exception thrown for a document using null model id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
null, toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions().setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage());
}, INVOICE_6_PDF);
}
/**
* Verifies an exception thrown for an empty model id when recognizing custom form from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
"", toFluxByteBuffer(data), dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage());
}, INVOICE_6_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) ->
beginTrainingLabeledRunner((training, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(training, useTrainingLabels,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class,
() -> client.beginRecognizeCustomFormsFromUrl(
createdModel.getModelId(), invalidSourceUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = formRecognizerException.getErrorInformation().get(0);
assertEquals(URL_BADLY_FORMATTED_ERROR_CODE, errorInformation.getErrorCode());
}));
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> beginTrainingLabeledRunner(
(trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
}
/**
* Verify custom form for a data stream of multi-page labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormMultiPageLabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
true, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
String modelId = trainingPoller.getFinalResult().getModelId();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
modelId, toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataLabeled(syncPoller.getFinalResult(), modelId);
}), MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithSelectionMark(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginSelectionMarkTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(data),
dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), SELECTION_MARK_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), INVOICE_6_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid include field elements
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, false);
}), INVOICE_6_PDF);
}
/**
* Verify custom form for a data stream of multi-page unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion)
.beginTraining(trainingFilesUrl, false,
new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataUnlabeled(syncPoller.getFinalResult());
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies custom form data for a JPG content type with unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), FORM_JPG);
}
/**
* Verifies custom form data for a blank PDF content type with unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), BLANK_PDF);
}
/**
* Verifies custom form data for an URL document data without labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), FORM_JPG);
}
/**
* Verifies custom form data for an URL document data without labeled data and include element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, false);
}), FORM_JPG);
}
/**
* Verify custom form for an URL of multi-page unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(fileUrl ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
false, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(trainingPoller.getFinalResult().getModelId(), fileUrl,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataUnlabeled(syncPoller.getFinalResult());
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
StepVerifier.create(client.beginRecognizeCustomFormsFromUrl(createdModel.getModelId(), INVALID_URL,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode)))
.verifyErrorSatisfies(throwable -> {
final HttpResponseException httpResponseException = (HttpResponseException) throwable;
final FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(INVALID_SOURCE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
});
}
/**
* Verifies an exception thrown for a null model id when recognizing custom form from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
Exception ex = assertThrows(RuntimeException.class, () ->
client.beginRecognizeCustomFormsFromUrl(null, fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies an exception thrown for an empty model id for recognizing custom forms from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () ->
client.beginRecognizeCustomFormsFromUrl("", fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies custom form data for an URL document data with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies custom form data for an URL document data with labeled data and include element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
}
/**
* Verify custom form for an URL of multi-page labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion)
.beginTraining(trainingFilesUrl, true,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
String modelId = trainingPoller.getFinalResult().getModelId();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
modelId, fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataLabeled(syncPoller.getFinalResult(), modelId);
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with \
* encoded blank space as input data to recognize a custom form from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, sourceUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verify that custom form with invalid model id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlNonExistModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, fileUrl,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_MODEL_ID_ERROR_CODE, errorInformation.getErrorCode());
}, FORM_JPG);
}
/**
* Verify that custom form with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(data), dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals("Invalid input file.", errorInformation.getMessage());
}));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledDataWithSelectionMark(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> beginSelectionMarkTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(trainingPoller.getFinalResult().getModelId(), fileUrl,
new RecognizeCustomFormsOptions().setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), SELECTION_MARK_PDF);
}
/**
* Verifies business card data from a document using file data as source.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataNullData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
assertThrows(NullPointerException.class, () -> client.beginRecognizeBusinessCards(
null, 0).getSyncPoller());
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data from a document using file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data from a document using PNG file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_PNG)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_PNG);
}
/**
* Verifies business card data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
/**
* Verify that business card recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verify business card recognition with multipage pdf.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageBusinessCard(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data),
dataLength,
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageBusinessData(syncPoller.getFinalResult());
}, MULTIPAGE_BUSINESS_CARD_PDF);
}
/**
* Verifies business card data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize business card from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCardsFromUrl(invalidSourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies business card data for a document using source as file url and include content when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data for a document using source as PNG file url and include element references when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_PNG);
}
/**
* Verify business card recognition with multipage pdf url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageBusinessData(syncPoller.getFinalResult());
}, MULTIPAGE_BUSINESS_CARD_PDF);
}
/**
* Verify locale parameter passed when specified by user.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void receiptValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verify locale parameter passed when specified by user for business cards API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void businessCardValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies invoice data recognition for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies content type will be auto detected when using invoice API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(getContentDetectionFileData(filePath)),
dataLength,
new RecognizeInvoicesOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies invoice data for a document using source as as input stream data and text content when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies invoice data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
/**
* Verify that invoice recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller()
.getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verify invoice data recognition with multipage pdf.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageInvoice(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageInvoiceData(syncPoller.getFinalResult());
}, MULTIPAGE_VENDOR_INVOICE_PDF);
}
/**
* Verifies invoice card data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner((sourceUrl) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize invoice card from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((sourceUrl)
-> assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller()));
}
/**
* Verifies invoice data for a document using source as file url and include form element references
* when includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, INVOICE);
}, INVOICE_PDF);
}
/**
* Verify locale parameter passed when specified by user.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void invoiceValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
final SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)
.setLocale(FormRecognizerLocale.EN_US))
.getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, INVOICE_PDF);
}
} | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient getFormRecognizerAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormRecognizerClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormTrainingClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
/**
* Verifies receipt data from a document using file data as source.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataNullData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
assertThrows(NullPointerException.class, () -> client.beginRecognizeReceipts(null, 0)
.getSyncPoller());
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeReceiptsOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data from a document using file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(
toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data from a document using PNG file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_PNG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_PNG);
}
/**
* Verifies receipt data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(
toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageReceiptData(syncPoller.getFinalResult());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verify that receipt recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies receipt data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize receipt from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceiptsFromUrl(invalidSourceUrl, new RecognizeReceiptsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies receipt data for a document using source as file url and include content when includeFieldElements is
* true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(
sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data for a document using source as PNG file url and include element references when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_PNG);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(
fileUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageReceiptData(syncPoller.getFinalResult());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
assertThrows(NullPointerException.class, () -> client.beginRecognizeContent(null, 0)
.getSyncPoller());
}
/**
* Verifies content type will be auto detected when using content/layout API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies blank form file is still a valid file to process
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, BLANK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verify that content recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContent(toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_ERROR_CODE, errorInformation.getErrorCode());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithSelectionMarks(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, SELECTION_MARK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Collections.singletonList("1")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(1, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPages(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Arrays.asList("1", "2")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(2, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPageRange(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Arrays.asList("1-2", "3")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(3, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentAppearance(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(TextStyleName.OTHER,
formPages.get(0).getLines().get(0).getAppearance().getStyle().getName());
}, FORM_JPG);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize a content from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies layout data for a pdf url
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, INVOICE_6_PDF);
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(invalidSourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner((formUrl) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(
formUrl, new RecognizeContentOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithSelectionMarksFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, SELECTION_MARK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeGermanContentFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode)
.setLanguage(FormRecognizerLanguage.DE))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
validateNetworkCallRecord("language", "de");
}, CONTENT_GERMAN_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentIncorrectLanguageFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(sourceUrl -> {
HttpResponseException exception
= assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode)
.setLanguage(FormRecognizerLanguage.fromString("language")))
.getSyncPoller());
assertEquals(((FormRecognizerErrorInformation) exception.getValue()).getErrorCode(),
"NotSupportedLanguage");
}, CONTENT_GERMAN_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
/**
* Verifies custom form data for a JPG content type with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies custom form data for a blank PDF content type with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), BLANK_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id,
* excluding element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller()
.setPollInterval(durationTestMode);
syncPoller.waitForCompletion();
assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
syncPoller.getFinalResult().getModelId(), null, dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller());
}), INVOICE_6_PDF);
}
/**
* Verifies an exception thrown for a document using null model id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
null, toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage());
}, INVOICE_6_PDF);
}
/**
* Verifies an exception thrown for an empty model id when recognizing custom form from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
"", toFluxByteBuffer(data), dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage());
}, INVOICE_6_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) ->
beginTrainingLabeledRunner((training, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(training, useTrainingLabels,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class,
() -> client.beginRecognizeCustomFormsFromUrl(
createdModel.getModelId(), invalidSourceUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = formRecognizerException.getErrorInformation().get(0);
assertEquals(URL_BADLY_FORMATTED_ERROR_CODE, errorInformation.getErrorCode());
}));
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> beginTrainingLabeledRunner(
(trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
}
/**
* Verify custom form for a data stream of multi-page labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormMultiPageLabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
true, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
String modelId = trainingPoller.getFinalResult().getModelId();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
modelId, toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataLabeled(syncPoller.getFinalResult(), modelId);
}), MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithSelectionMark(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginSelectionMarkTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(data),
dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), SELECTION_MARK_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), INVOICE_6_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid include field elements
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, false);
}), INVOICE_6_PDF);
}
/**
* Verify custom form for a data stream of multi-page unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion)
.beginTraining(trainingFilesUrl, false,
new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataUnlabeled(syncPoller.getFinalResult());
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies custom form data for a JPG content type with unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), FORM_JPG);
}
/**
* Verifies custom form data for a blank PDF content type with unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), BLANK_PDF);
}
/**
* Verifies custom form data for an URL document data without labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), FORM_JPG);
}
/**
* Verifies custom form data for an URL document data without labeled data and include element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, false);
}), FORM_JPG);
}
/**
* Verify custom form for an URL of multi-page unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(fileUrl ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
false, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(trainingPoller.getFinalResult().getModelId(), fileUrl,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataUnlabeled(syncPoller.getFinalResult());
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
StepVerifier.create(client.beginRecognizeCustomFormsFromUrl(createdModel.getModelId(), INVALID_URL,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode)))
.verifyErrorSatisfies(throwable -> {
final HttpResponseException httpResponseException = (HttpResponseException) throwable;
final FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(INVALID_SOURCE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
});
}
/**
* Verifies an exception thrown for a null model id when recognizing custom form from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
Exception ex = assertThrows(RuntimeException.class, () ->
client.beginRecognizeCustomFormsFromUrl(null, fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies an exception thrown for an empty model id for recognizing custom forms from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () ->
client.beginRecognizeCustomFormsFromUrl("", fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies custom form data for an URL document data with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies custom form data for an URL document data with labeled data and include element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
}
/**
* Verify custom form for an URL of multi-page labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion)
.beginTraining(trainingFilesUrl, true,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
String modelId = trainingPoller.getFinalResult().getModelId();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
modelId, fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataLabeled(syncPoller.getFinalResult(), modelId);
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with \
* encoded blank space as input data to recognize a custom form from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client
.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, sourceUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verify that custom form with invalid model id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlNonExistModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, fileUrl,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode)).getSyncPoller()
.getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_MODEL_ID_ERROR_CODE, errorInformation.getErrorCode());
}, FORM_JPG);
}
/**
* Verify that custom form with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(data), dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals("Invalid input file.", errorInformation.getMessage());
}));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledDataWithSelectionMark(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> beginSelectionMarkTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(trainingPoller.getFinalResult().getModelId(), fileUrl,
new RecognizeCustomFormsOptions().setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), SELECTION_MARK_PDF);
}
/**
* Verifies business card data from a document using file data as source.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataNullData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
assertThrows(NullPointerException.class, () -> client.beginRecognizeBusinessCards(
null, 0).getSyncPoller());
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data from a document using file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data from a document using PNG file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_PNG)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_PNG);
}
/**
* Verifies business card data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
/**
* Verify that business card recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verify business card recognition with multipage pdf.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageBusinessCard(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data),
dataLength,
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageBusinessData(syncPoller.getFinalResult());
}, MULTIPAGE_BUSINESS_CARD_PDF);
}
/**
* Verifies business card data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize business card from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCardsFromUrl(invalidSourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies business card data for a document using source as file url and include content when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data for a document using source as PNG file url and include element references when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_PNG);
}
/**
* Verify business card recognition with multipage pdf url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageBusinessData(syncPoller.getFinalResult());
}, MULTIPAGE_BUSINESS_CARD_PDF);
}
/**
* Verify locale parameter passed when specified by user.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void receiptValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verify locale parameter passed when specified by user for business cards API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void businessCardValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies invoice data recognition for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies content type will be auto detected when using invoice API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(getContentDetectionFileData(filePath)),
dataLength,
new RecognizeInvoicesOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies invoice data for a document using source as as input stream data and text content when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies invoice data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
/**
* Verify that invoice recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller()
.getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verify invoice data recognition with multipage pdf.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageInvoice(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageInvoiceData(syncPoller.getFinalResult());
}, MULTIPAGE_VENDOR_INVOICE_PDF);
}
/**
* Verifies invoice card data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner((sourceUrl) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize invoice card from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((sourceUrl)
-> assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller()));
}
/**
* Verifies invoice data for a document using source as file url and include form element references
* when includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, INVOICE);
}, INVOICE_PDF);
}
/**
* Verify locale parameter passed when specified by user.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void invoiceValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
final SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)
.setLocale(FormRecognizerLocale.EN_US))
.getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, INVOICE_PDF);
}
} |
yes, wanted to use the FORM, updated the type. | public void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data),
dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
} | }), FORM_JPG); | public void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client
.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data),
dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
} | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient getFormRecognizerAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormRecognizerClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormTrainingClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
/**
* Verifies receipt data from a document using file data as source.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataNullData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
assertThrows(NullPointerException.class, () -> client.beginRecognizeReceipts(null, 0)
.getSyncPoller());
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeReceiptsOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data from a document using file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(
toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data from a document using PNG file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_PNG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_PNG);
}
/**
* Verifies receipt data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(
toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageReceiptData(syncPoller.getFinalResult());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verify that receipt recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies receipt data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize receipt from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceiptsFromUrl(invalidSourceUrl, new RecognizeReceiptsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies receipt data for a document using source as file url and include content when includeFieldElements is
* true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(
sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data for a document using source as PNG file url and include element references when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_PNG);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(
fileUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageReceiptData(syncPoller.getFinalResult());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
assertThrows(NullPointerException.class, () -> client.beginRecognizeContent(null, 0)
.getSyncPoller());
}
/**
* Verifies content type will be auto detected when using content/layout API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies blank form file is still a valid file to process
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, BLANK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verify that content recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContent(toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_ERROR_CODE, errorInformation.getErrorCode());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithSelectionMarks(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, SELECTION_MARK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Collections.singletonList("1")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(1, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPages(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Arrays.asList("1", "2")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(2, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPageRange(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Arrays.asList("1-2", "3")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(3, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentAppearance(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(TextStyleName.OTHER,
formPages.get(0).getLines().get(0).getAppearance().getStyle().getName());
}, FORM_JPG);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize a content from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies layout data for a pdf url
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, INVOICE_6_PDF);
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(invalidSourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner((formUrl) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(
formUrl, new RecognizeContentOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithSelectionMarksFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, SELECTION_MARK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeGermanContentFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode)
.setLanguage(FormRecognizerLanguage.DE))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
validateNetworkCallRecord("language", "de");
}, CONTENT_GERMAN_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentIncorrectLanguageFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(sourceUrl -> {
HttpResponseException exception
= assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode)
.setLanguage(FormRecognizerLanguage.fromString("language")))
.getSyncPoller());
assertEquals(((FormRecognizerErrorInformation) exception.getValue()).getErrorCode(), "NotSupportedLanguage");
}, CONTENT_GERMAN_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
/**
* Verifies custom form data for a JPG content type with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies custom form data for a blank PDF content type with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), BLANK_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id,
* excluding element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller()
.setPollInterval(durationTestMode);
syncPoller.waitForCompletion();
assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
syncPoller.getFinalResult().getModelId(), null, dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller());
}), INVOICE_6_PDF);
}
/**
* Verifies an exception thrown for a document using null model id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
null, toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions().setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage());
}, INVOICE_6_PDF);
}
/**
* Verifies an exception thrown for an empty model id when recognizing custom form from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
"", toFluxByteBuffer(data), dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage());
}, INVOICE_6_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) ->
beginTrainingLabeledRunner((training, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(training, useTrainingLabels,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class,
() -> client.beginRecognizeCustomFormsFromUrl(
createdModel.getModelId(), invalidSourceUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = formRecognizerException.getErrorInformation().get(0);
assertEquals(URL_BADLY_FORMATTED_ERROR_CODE, errorInformation.getErrorCode());
}));
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> beginTrainingLabeledRunner(
(trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
}
/**
* Verify custom form for a data stream of multi-page labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormMultiPageLabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
true, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
String modelId = trainingPoller.getFinalResult().getModelId();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
modelId, toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataLabeled(syncPoller.getFinalResult(), modelId);
}), MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithSelectionMark(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginSelectionMarkTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(data),
dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), SELECTION_MARK_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), INVOICE_6_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid include field elements
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, false);
}), INVOICE_6_PDF);
}
/**
* Verify custom form for a data stream of multi-page unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion)
.beginTraining(trainingFilesUrl, false,
new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataUnlabeled(syncPoller.getFinalResult());
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies custom form data for a JPG content type with unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), FORM_JPG);
}
/**
* Verifies custom form data for a blank PDF content type with unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), BLANK_PDF);
}
/**
* Verifies custom form data for an URL document data without labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), FORM_JPG);
}
/**
* Verifies custom form data for an URL document data without labeled data and include element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, false);
}), FORM_JPG);
}
/**
* Verify custom form for an URL of multi-page unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(fileUrl ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
false, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(trainingPoller.getFinalResult().getModelId(), fileUrl,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataUnlabeled(syncPoller.getFinalResult());
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
StepVerifier.create(client.beginRecognizeCustomFormsFromUrl(createdModel.getModelId(), INVALID_URL,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode)))
.verifyErrorSatisfies(throwable -> {
final HttpResponseException httpResponseException = (HttpResponseException) throwable;
final FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(INVALID_SOURCE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
});
}
/**
* Verifies an exception thrown for a null model id when recognizing custom form from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
Exception ex = assertThrows(RuntimeException.class, () ->
client.beginRecognizeCustomFormsFromUrl(null, fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies an exception thrown for an empty model id for recognizing custom forms from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () ->
client.beginRecognizeCustomFormsFromUrl("", fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies custom form data for an URL document data with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies custom form data for an URL document data with labeled data and include element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
}
/**
* Verify custom form for an URL of multi-page labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion)
.beginTraining(trainingFilesUrl, true,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
String modelId = trainingPoller.getFinalResult().getModelId();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl(
modelId, fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataLabeled(syncPoller.getFinalResult(), modelId);
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with \
* encoded blank space as input data to recognize a custom form from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, sourceUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verify that custom form with invalid model id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlNonExistModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, fileUrl,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_MODEL_ID_ERROR_CODE, errorInformation.getErrorCode());
}, FORM_JPG);
}
/**
* Verify that custom form with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(data), dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals("Invalid input file.", errorInformation.getMessage());
}));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledDataWithSelectionMark(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> beginSelectionMarkTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(trainingPoller.getFinalResult().getModelId(), fileUrl,
new RecognizeCustomFormsOptions().setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), SELECTION_MARK_PDF);
}
/**
* Verifies business card data from a document using file data as source.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataNullData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
assertThrows(NullPointerException.class, () -> client.beginRecognizeBusinessCards(
null, 0).getSyncPoller());
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data from a document using file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data from a document using PNG file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_PNG)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_PNG);
}
/**
* Verifies business card data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
/**
* Verify that business card recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verify business card recognition with multipage pdf.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageBusinessCard(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data),
dataLength,
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageBusinessData(syncPoller.getFinalResult());
}, MULTIPAGE_BUSINESS_CARD_PDF);
}
/**
* Verifies business card data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize business card from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCardsFromUrl(invalidSourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies business card data for a document using source as file url and include content when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data for a document using source as PNG file url and include element references when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_PNG);
}
/**
* Verify business card recognition with multipage pdf url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageBusinessData(syncPoller.getFinalResult());
}, MULTIPAGE_BUSINESS_CARD_PDF);
}
/**
* Verify locale parameter passed when specified by user.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void receiptValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verify locale parameter passed when specified by user for business cards API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void businessCardValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies invoice data recognition for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies content type will be auto detected when using invoice API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(getContentDetectionFileData(filePath)),
dataLength,
new RecognizeInvoicesOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies invoice data for a document using source as as input stream data and text content when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies invoice data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
/**
* Verify that invoice recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller()
.getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verify invoice data recognition with multipage pdf.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageInvoice(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageInvoiceData(syncPoller.getFinalResult());
}, MULTIPAGE_VENDOR_INVOICE_PDF);
}
/**
* Verifies invoice card data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner((sourceUrl) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize invoice card from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((sourceUrl)
-> assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller()));
}
/**
* Verifies invoice data for a document using source as file url and include form element references
* when includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, INVOICE);
}, INVOICE_PDF);
}
/**
* Verify locale parameter passed when specified by user.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void invoiceValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
final SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)
.setLocale(FormRecognizerLocale.EN_US))
.getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, INVOICE_PDF);
}
} | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient getFormRecognizerAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormRecognizerClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormTrainingClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
/**
* Verifies receipt data from a document using file data as source.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataNullData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
assertThrows(NullPointerException.class, () -> client.beginRecognizeReceipts(null, 0)
.getSyncPoller());
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeReceiptsOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data from a document using file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(
toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data from a document using PNG file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_PNG).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_PNG);
}
/**
* Verifies receipt data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(
toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageReceiptData(syncPoller.getFinalResult());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verify that receipt recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceipts(toFluxByteBuffer(data), dataLength, new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies receipt data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize receipt from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeReceiptsFromUrl(invalidSourceUrl, new RecognizeReceiptsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies receipt data for a document using source as file url and include content when includeFieldElements is
* true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(
sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies receipt data for a document using source as PNG file url and include element references when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT);
}, RECEIPT_CONTOSO_PNG);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@Disabled
public void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(
fileUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageReceiptData(syncPoller.getFinalResult());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
assertThrows(NullPointerException.class, () -> client.beginRecognizeContent(null, 0)
.getSyncPoller());
}
/**
* Verifies content type will be auto detected when using content/layout API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies blank form file is still a valid file to process
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, BLANK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verify that content recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContent(toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_ERROR_CODE, errorInformation.getErrorCode());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithSelectionMarks(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, SELECTION_MARK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Collections.singletonList("1")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(1, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPages(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Arrays.asList("1", "2")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(2, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithPageRange(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(toFluxByteBuffer(data),
dataLength,
new RecognizeContentOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)
.setPages(Arrays.asList("1-2", "3")))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(3, formPages.size());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentAppearance(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
toFluxByteBuffer(data), dataLength, new RecognizeContentOptions()
.setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
List<FormPage> formPages = syncPoller.getFinalResult();
validateContentResultData(formPages, false);
assertEquals(TextStyleName.OTHER,
formPages.get(0).getLines().get(0).getAppearance().getStyle().getName());
}, FORM_JPG);
}
/**
* Verifies layout data for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, FORM_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize a content from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies layout data for a pdf url
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, INVOICE_6_PDF);
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(invalidSourceUrl, new RecognizeContentOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner((formUrl) -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(
formUrl, new RecognizeContentOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentWithSelectionMarksFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
}, SELECTION_MARK_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeGermanContentFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode)
.setLanguage(FormRecognizerLanguage.DE))
.getSyncPoller();
syncPoller.waitForCompletion();
validateContentResultData(syncPoller.getFinalResult(), false);
validateNetworkCallRecord("language", "de");
}, CONTENT_GERMAN_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeContentIncorrectLanguageFromUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(sourceUrl -> {
HttpResponseException exception
= assertThrows(HttpResponseException.class,
() -> client.beginRecognizeContentFromUrl(sourceUrl,
new RecognizeContentOptions().setPollInterval(durationTestMode)
.setLanguage(FormRecognizerLanguage.fromString("language")))
.getSyncPoller());
assertEquals(((FormRecognizerErrorInformation) exception.getValue()).getErrorCode(),
"NotSupportedLanguage");
}, CONTENT_GERMAN_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
/**
* Verifies custom form data for a JPG content type with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies custom form data for a blank PDF content type with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), BLANK_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id,
* excluding element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller()
.setPollInterval(durationTestMode);
syncPoller.waitForCompletion();
assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
syncPoller.getFinalResult().getModelId(), null, dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller());
}), INVOICE_6_PDF);
}
/**
* Verifies an exception thrown for a document using null model id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
null, toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage());
}, INVOICE_6_PDF);
}
/**
* Verifies an exception thrown for an empty model id when recognizing custom form from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(
"", toFluxByteBuffer(data), dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage());
}, INVOICE_6_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) ->
beginTrainingLabeledRunner((training, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(training, useTrainingLabels,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class,
() -> client.beginRecognizeCustomFormsFromUrl(
createdModel.getModelId(), invalidSourceUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = formRecognizerException.getErrorInformation().get(0);
assertEquals(URL_BADLY_FORMATTED_ERROR_CODE, errorInformation.getErrorCode());
}));
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> beginTrainingLabeledRunner(
(trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
}
/**
* Verify custom form for a data stream of multi-page labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormMultiPageLabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
true, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
String modelId = trainingPoller.getFinalResult().getModelId();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
modelId, toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataLabeled(syncPoller.getFinalResult(), modelId);
}), MULTIPAGE_INVOICE_PDF);
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormLabeledDataWithSelectionMark(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginSelectionMarkTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(data),
dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), SELECTION_MARK_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid labeled model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), INVOICE_6_PDF);
}
/**
* Verifies custom form data for a document using source as input stream data and valid include field elements
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, false);
}), INVOICE_6_PDF);
}
/**
* Verify custom form for a data stream of multi-page unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion)
.beginTraining(trainingFilesUrl, false,
new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataUnlabeled(syncPoller.getFinalResult());
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies custom form data for a JPG content type with unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), FORM_JPG);
}
/**
* Verifies custom form data for a blank PDF content type with unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomForms(
trainingPoller.getFinalResult().getModelId(), toFluxByteBuffer(data), dataLength,
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), BLANK_PDF);
}
/**
* Verifies custom form data for an URL document data without labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, false);
}), FORM_JPG);
}
/**
* Verifies custom form data for an URL document data without labeled data and include element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, false);
}), FORM_JPG);
}
/**
* Verify custom form for an URL of multi-page unlabeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
testingContainerUrlRunner(fileUrl ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
false, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(trainingPoller.getFinalResult().getModelId(), fileUrl,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataUnlabeled(syncPoller.getFinalResult());
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
StepVerifier.create(client.beginRecognizeCustomFormsFromUrl(createdModel.getModelId(), INVALID_URL,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode)))
.verifyErrorSatisfies(throwable -> {
final HttpResponseException httpResponseException = (HttpResponseException) throwable;
final FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(INVALID_SOURCE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
});
}
/**
* Verifies an exception thrown for a null model id when recognizing custom form from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
Exception ex = assertThrows(RuntimeException.class, () ->
client.beginRecognizeCustomFormsFromUrl(null, fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies an exception thrown for an empty model id for recognizing custom forms from URL.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () ->
client.beginRecognizeCustomFormsFromUrl("", fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage());
}, MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies custom form data for an URL document data with labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), false, true);
}), FORM_JPG);
}
/**
* Verifies custom form data for an URL document data with labeled data and include element references.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true).setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), FORM_JPG);
}
/**
* Verify custom form for an URL of multi-page labeled data
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl ->
beginTrainingMultipageRunner((trainingFilesUrl) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion)
.beginTraining(trainingFilesUrl, true,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
String modelId = trainingPoller.getFinalResult().getModelId();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(
modelId, fileUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultiPageDataLabeled(syncPoller.getFinalResult(), modelId);
}), MULTIPAGE_INVOICE_PDF);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with \
* encoded blank space as input data to recognize a custom form from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client
.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, sourceUrl, new RecognizeCustomFormsOptions()
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verify that custom form with invalid model id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlNonExistModelId(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, fileUrl,
new RecognizeCustomFormsOptions().setPollInterval(durationTestMode)).getSyncPoller()
.getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_MODEL_ID_ERROR_CODE, errorInformation.getErrorCode());
}, FORM_JPG);
}
/**
* Verify that custom form with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) ->
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(),
toFluxByteBuffer(data), dataLength, new RecognizeCustomFormsOptions()
.setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals("Invalid input file.", errorInformation.getMessage());
}));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeCustomFormUrlLabeledDataWithSelectionMark(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(fileUrl -> beginSelectionMarkTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
trainingPoller.waitForCompletion();
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeCustomFormsFromUrl(trainingPoller.getFinalResult().getModelId(), fileUrl,
new RecognizeCustomFormsOptions().setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateRecognizedResult(syncPoller.getFinalResult(), true, true);
}), SELECTION_MARK_PDF);
}
/**
* Verifies business card data from a document using file data as source.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies an exception thrown for a document using null data value.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataNullData(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
assertThrows(NullPointerException.class, () -> client.beginRecognizeBusinessCards(
null, 0).getSyncPoller());
}
/**
* Verifies content type will be auto detected when using custom form API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(getContentDetectionFileData(filePath)), dataLength,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data from a document using file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data from a document using PNG file data as source and including element reference details.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_PNG)
.setFieldElementsIncluded(true).setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_PNG);
}
/**
* Verifies business card data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
/**
* Verify that business card recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCards(toFluxByteBuffer(data), dataLength,
new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verify business card recognition with multipage pdf.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageBusinessCard(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCards(toFluxByteBuffer(data),
dataLength,
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageBusinessData(syncPoller.getFinalResult());
}, MULTIPAGE_BUSINESS_CARD_PDF);
}
/**
* Verifies business card data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize business card from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeBusinessCardsFromUrl(invalidSourceUrl,
new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode))
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) errorResponseException.getValue();
assertEquals(INVALID_IMAGE_URL_ERROR_CODE, errorInformation.getErrorCode());
});
}
/**
* Verifies business card data for a document using source as file url and include content when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_JPG);
}
/**
* Verifies business card data for a document using source as PNG file url and include element references when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, BUSINESS_CARD);
}, BUSINESS_CARD_PNG);
}
/**
* Verify business card recognition with multipage pdf url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageBusinessData(syncPoller.getFinalResult());
}, MULTIPAGE_BUSINESS_CARD_PDF);
}
/**
* Verify locale parameter passed when specified by user.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void receiptValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeReceiptsFromUrl(sourceUrl,
new RecognizeReceiptsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verify locale parameter passed when specified by user for business cards API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void businessCardValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeBusinessCardsFromUrl(sourceUrl,
new RecognizeBusinessCardsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, RECEIPT_CONTOSO_JPG);
}
/**
* Verifies invoice data recognition for a document using source as input stream data.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies content type will be auto detected when using invoice API with input stream data overload.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataWithContentTypeAutoDetection(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
localFilePathRunner((filePath, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(getContentDetectionFileData(filePath)),
dataLength,
new RecognizeInvoicesOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies invoice data for a document using source as as input stream data and text content when
* includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies invoice data from a document using blank PDF.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceDataWithBlankPdf(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
}, BLANK_PDF);
}
/**
* Verify that invoice recognition with damaged PDF file.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
damagedPdfDataRunner((data, dataLength) -> {
HttpResponseException httpResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller()
.getFinalResult());
FormRecognizerErrorInformation errorInformation =
(FormRecognizerErrorInformation) httpResponseException.getValue();
assertEquals(BAD_ARGUMENT_CODE, errorInformation.getErrorCode());
});
}
/**
* Verify invoice data recognition with multipage pdf.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeMultipageInvoice(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
dataRunner((data, dataLength) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoices(toFluxByteBuffer(data),
dataLength,
new RecognizeInvoicesOptions()
.setContentType(APPLICATION_PDF)
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validateMultipageInvoiceData(syncPoller.getFinalResult());
}, MULTIPAGE_VENDOR_INVOICE_PDF);
}
/**
* Verifies invoice card data for a document using source as file url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner((sourceUrl) -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), false, INVOICE);
}, INVOICE_PDF);
}
/**
* Verifies encoded blank url must stay same when sent to service for a document using invalid source url with
* encoded blank space as input data to recognize invoice card from url API.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
encodedBlankSpaceSourceUrlRunner(sourceUrl -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller());
validateExceptionSource(errorResponseException);
});
}
/**
* Verifies that an exception is thrown for invalid source url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceInvalidSourceUrl(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((sourceUrl)
-> assertThrows(HttpResponseException.class,
() -> client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)).getSyncPoller()));
}
/**
* Verifies invoice data for a document using source as file url and include form element references
* when includeFieldElements is true.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void recognizeInvoiceFromUrlIncludeFieldElements(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(true)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validatePrebuiltResultData(syncPoller.getFinalResult(), true, INVOICE);
}, INVOICE_PDF);
}
/**
* Verify locale parameter passed when specified by user.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void invoiceValidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
urlRunner(sourceUrl -> {
final SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
client.beginRecognizeInvoicesFromUrl(sourceUrl,
new RecognizeInvoicesOptions()
.setPollInterval(durationTestMode)
.setLocale(FormRecognizerLocale.EN_US))
.getSyncPoller();
syncPoller.getFinalResult();
validateNetworkCallRecord("locale", "en-US");
}, INVOICE_PDF);
}
} |
IMO this should just throw to capture any future regressions early. | public static JsonSerializable instantiateFromObjectNodeAndType(ObjectNode objectNode, Class<?> klassType) {
if (klassType.equals(Document.class)) {
return new Document(objectNode);
}
if (klassType.equals(InternalObjectNode.class)) {
return new InternalObjectNode(objectNode);
}
if (klassType.equals(PartitionKeyRange.class)) {
return new PartitionKeyRange(objectNode);
}
if (klassType.equals(Range.class)) {
return new Range<>(objectNode);
}
if (klassType.equals(QueryInfo.class)) {
return new QueryInfo(objectNode);
}
if (klassType.equals(PartitionedQueryExecutionInfoInternal.class)) {
return new PartitionedQueryExecutionInfoInternal(objectNode);
}
if (klassType.equals(QueryItem.class)) {
return new QueryItem(objectNode);
}
if (klassType.equals(Address.class)) {
return new Address(objectNode);
}
if (klassType.equals(DatabaseAccount.class)) {
return new DatabaseAccount(objectNode);
}
if (klassType.equals(DatabaseAccountLocation.class)) {
return new DatabaseAccountLocation(objectNode);
}
if (klassType.equals(ReplicationPolicy.class)) {
return new ReplicationPolicy(objectNode);
}
if (klassType.equals(ConsistencyPolicy.class)) {
return new ConsistencyPolicy(objectNode);
}
if (klassType.equals(DocumentCollection.class)) {
return new DocumentCollection(objectNode);
}
if (klassType.equals(Database.class)) {
return new Database(objectNode);
} else {
try {
return (JsonSerializable) klassType.getDeclaredConstructor(String.class)
.newInstance(Utils.toJson(Utils.getSimpleObjectMapper(), objectNode));
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
}
} | try { | public static JsonSerializable instantiateFromObjectNodeAndType(ObjectNode objectNode, Class<?> klassType) {
if (klassType.equals(Document.class)) {
return new Document(objectNode);
}
if (klassType.equals(InternalObjectNode.class)) {
return new InternalObjectNode(objectNode);
}
if (klassType.equals(PartitionKeyRange.class)) {
return new PartitionKeyRange(objectNode);
}
if (klassType.equals(Range.class)) {
return new Range<>(objectNode);
}
if (klassType.equals(QueryInfo.class)) {
return new QueryInfo(objectNode);
}
if (klassType.equals(PartitionedQueryExecutionInfoInternal.class)) {
return new PartitionedQueryExecutionInfoInternal(objectNode);
}
if (klassType.equals(QueryItem.class)) {
return new QueryItem(objectNode);
}
if (klassType.equals(Address.class)) {
return new Address(objectNode);
}
if (klassType.equals(DatabaseAccount.class)) {
return new DatabaseAccount(objectNode);
}
if (klassType.equals(DatabaseAccountLocation.class)) {
return new DatabaseAccountLocation(objectNode);
}
if (klassType.equals(ReplicationPolicy.class)) {
return new ReplicationPolicy(objectNode);
}
if (klassType.equals(ConsistencyPolicy.class)) {
return new ConsistencyPolicy(objectNode);
}
if (klassType.equals(DocumentCollection.class)) {
return new DocumentCollection(objectNode);
}
if (klassType.equals(Database.class)) {
return new Database(objectNode);
} else {
try {
return (JsonSerializable) klassType.getDeclaredConstructor(String.class)
.newInstance(Utils.toJson(Utils.getSimpleObjectMapper(), objectNode));
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
}
} | class JsonSerializable {
private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper();
private static final Logger LOGGER = LoggerFactory.getLogger(JsonSerializable.class);
transient ObjectNode propertyBag = null;
private ObjectMapper om;
public JsonSerializable() {
this.propertyBag = OBJECT_MAPPER.createObjectNode();
}
/**
* Constructor.
*
* @param jsonString the json string that represents the JsonSerializable.
* @param objectMapper the custom object mapper
*/
protected JsonSerializable(String jsonString, ObjectMapper objectMapper) {
this.propertyBag = fromJson(jsonString);
this.om = objectMapper;
}
/**
* Constructor.
*
* @param jsonString the json string that represents the JsonSerializable.
*/
public JsonSerializable(String jsonString) {
this.propertyBag = fromJson(jsonString);
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the {@link JsonSerializable}
*/
public JsonSerializable(ObjectNode objectNode) {
this.propertyBag = objectNode;
}
protected JsonSerializable(ByteBuffer byteBuffer) {
this.propertyBag = fromJson(byteBuffer);
}
protected JsonSerializable(byte[] bytes) {
this.propertyBag = fromJson(bytes);
}
private static void checkForValidPOJO(Class<?> c) {
if (c.isAnonymousClass() || c.isLocalClass()) {
throw new IllegalArgumentException(
String.format("%s can't be an anonymous or local class.", c.getName()));
}
if (c.isMemberClass() && !Modifier.isStatic(c.getModifiers())) {
throw new IllegalArgumentException(
String.format("%s must be static if it's a member class.", c.getName()));
}
}
public static Object getValue(JsonNode value) {
if (value.isValueNode()) {
switch (value.getNodeType()) {
case BOOLEAN:
return value.asBoolean();
case NUMBER:
if (value.isInt()) {
return value.asInt();
} else if (value.isLong()) {
return value.asLong();
} else if (value.isDouble()) {
return value.asDouble();
} else {
return value;
}
case STRING:
return value.asText();
default:
return value;
}
}
return value;
}
private ObjectMapper getMapper() {
if (this.om != null) {
return this.om;
}
return OBJECT_MAPPER;
}
void setMapper(ObjectMapper om) {
this.om = om;
}
@JsonIgnore
public Logger getLogger() {
return LOGGER;
}
public void populatePropertyBag() {
}
/**
* Returns the propertybag(JsonNode) in a hashMap
*
* @return the HashMap.
*/
@SuppressWarnings("unchecked")
public Map<String, Object> getMap() {
return getMapper().convertValue(this.propertyBag, HashMap.class);
}
@SuppressWarnings("unchecked")
public <T> Map<String, T> getMap(String propertyKey) {
if (this.propertyBag.has(propertyKey)) {
Object value = this.get(propertyKey);
return (Map<String, T>) getMapper().convertValue(value, HashMap.class);
}
return null;
}
/**
* Checks whether a property exists.
*
* @param propertyName the property to look up.
* @return true if the property exists.
*/
public boolean has(String propertyName) {
return this.propertyBag.has(propertyName);
}
/**
* Removes a value by propertyName.
*
* @param propertyName the property to remove.
*/
public void remove(String propertyName) {
this.propertyBag.remove(propertyName);
}
/**
* Sets the value of a property.
*
* @param <T> the type of the object.
* @param propertyName the property to set.
* @param value the value of the property.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public <T> void set(String propertyName, T value) {
if (value == null) {
this.propertyBag.putNull(propertyName);
} else if (value instanceof Collection) {
ArrayNode jsonArray = propertyBag.arrayNode();
this.internalSetCollection(propertyName, (Collection) value, jsonArray);
this.propertyBag.set(propertyName, jsonArray);
} else if (value instanceof JsonNode) {
this.propertyBag.set(propertyName, (JsonNode) value);
} else if (value instanceof JsonSerializable) {
JsonSerializable castedValue = (JsonSerializable) value;
castedValue.populatePropertyBag();
this.propertyBag.set(propertyName, castedValue.propertyBag);
} else if (containsJsonSerializable(value.getClass())) {
ModelBridgeInternal.populatePropertyBag(value);
this.propertyBag.set(propertyName, ModelBridgeInternal.getJsonSerializable(value).propertyBag);
} else {
this.propertyBag.set(propertyName, getMapper().valueToTree(value));
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
private <T> void internalSetCollection(String propertyName, Collection<T> collection, ArrayNode targetArray) {
for (T childValue : collection) {
if (childValue == null) {
targetArray.addNull();
} else if (childValue instanceof Collection) {
ArrayNode childArray = targetArray.addArray();
this.internalSetCollection(propertyName, (Collection) childValue, childArray);
} else if (childValue instanceof JsonNode) {
targetArray.add((JsonNode) childValue);
} else if (childValue instanceof JsonSerializable) {
JsonSerializable castedValue = (JsonSerializable) childValue;
castedValue.populatePropertyBag();
targetArray.add(castedValue.propertyBag != null ? castedValue.propertyBag
: this.getMapper().createObjectNode());
} else if (containsJsonSerializable(childValue.getClass())) {
ModelBridgeInternal.populatePropertyBag(childValue);
targetArray.add(ModelBridgeInternal.getJsonSerializable(childValue).propertyBag != null ?
ModelBridgeInternal.getJsonSerializable(childValue).propertyBag : this.getMapper().createObjectNode());
} else {
targetArray.add(this.getMapper().valueToTree(childValue));
}
}
}
/**
* Gets a property value as Object.
*
* @param propertyName the property to get.
* @return the value of the property.
*/
public Object get(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return getValue(this.propertyBag.get(propertyName));
} else {
return null;
}
}
/**
* Gets a string value.
*
* @param propertyName the property to get.
* @return the string value.
*/
public String getString(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asText();
} else {
return null;
}
}
/**
* Gets a boolean value.
*
* @param propertyName the property to get.
* @return the boolean value.
*/
@Nullable
public Boolean getBoolean(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asBoolean();
} else {
return null;
}
}
/**
* Gets an integer value.
*
* @param propertyName the property to get.
* @return the boolean value
*/
public Integer getInt(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asInt();
} else {
return null;
}
}
/**
* Gets a long value.
*
* @param propertyName the property to get.
* @return the long value
*/
protected Long getLong(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asLong();
} else {
return null;
}
}
/**
* Gets a double value.
*
* @param propertyName the property to get.
* @return the double value.
*/
public Double getDouble(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asDouble();
} else {
return null;
}
}
/**
* Gets an object value.
*
* @param <T> the type of the object.
* @param propertyName the property to get.
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object value.
* @throws IllegalStateException thrown if an error occurs
*/
@SuppressWarnings("unchecked")
public <T> T getObject(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
JsonNode jsonObj = propertyBag.get(propertyName);
if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c) || Object.class == c) {
return c.cast(getValue(jsonObj));
} else if (Enum.class.isAssignableFrom(c)) {
try {
String value = String.class.cast(getValue(jsonObj));
value = convertFromCamelCase.length > 0 && convertFromCamelCase[0]
? Strings.fromCamelCaseToUpperCase(value) : value;
return c.cast(c.getMethod("valueOf", String.class).invoke(null, value));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException("Failed to create enum.", e);
}
} else if (JsonSerializable.class.isAssignableFrom(c)) {
return (T) instantiateFromObjectNodeAndType((ObjectNode) jsonObj, c);
} else if (containsJsonSerializable(c)) {
return ModelBridgeInternal.instantiateByObjectNode((ObjectNode) jsonObj, c);
}
else {
JsonSerializable.checkForValidPOJO(c);
try {
return this.getMapper().treeToValue(jsonObj, c);
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
return null;
}
/**
* Gets an object List.
*
* @param <T> the type of the objects in the List.
* @param propertyName the property to get
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object collection.
* @throws IllegalStateException thrown if an error occurs
*/
@SuppressWarnings("unchecked")
public <T> List<T> getList(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
JsonNode jsonArray = this.propertyBag.get(propertyName);
ArrayList<T> result = new ArrayList<T>();
boolean isBaseClass = false;
boolean isEnumClass = false;
boolean isJsonSerializable = false;
boolean containsJsonSerializable = false;
if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c) || Object.class == c) {
isBaseClass = true;
} else if (Enum.class.isAssignableFrom(c)) {
isEnumClass = true;
} else if (JsonSerializable.class.isAssignableFrom(c)) {
isJsonSerializable = true;
} else if (containsJsonSerializable(c)) {
containsJsonSerializable = true;
} else {
JsonSerializable.checkForValidPOJO(c);
}
for (JsonNode n : jsonArray) {
if (isBaseClass) {
result.add(c.cast(getValue(n)));
} else if (isEnumClass) {
try {
String value = String.class.cast(getValue(n));
value = convertFromCamelCase.length > 0 && convertFromCamelCase[0]
? Strings.fromCamelCaseToUpperCase(value) : value;
result.add(c.cast(c.getMethod("valueOf", String.class).invoke(null, value)));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException("Failed to create enum.", e);
}
} else if (isJsonSerializable) {
T t = (T) instantiateFromObjectNodeAndType((ObjectNode) n, c);
result.add(t);
} else if (containsJsonSerializable) {
T t = ModelBridgeInternal.instantiateByObjectNode((ObjectNode) n, c);
result.add(t);
} else {
try {
result.add(this.getMapper().treeToValue(n, c));
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
return result;
}
return null;
}
/**
* Gets an object collection.
*
* @param <T> the type of the objects in the collection.
* @param propertyName the property to get
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object collection.
*/
public <T> Collection<T> getCollection(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
return getList(propertyName, c, convertFromCamelCase);
}
/**
* Gets a ObjectNode.
*
* @param propertyName the property to get.
* @return the ObjectNode.
*/
public ObjectNode getObject(String propertyName) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return (ObjectNode) this.propertyBag.get(propertyName);
}
return null;
}
/**
* Gets a ObjectNode collection.
*
* @param propertyName the property to get.
* @return the ObjectNode collection.
*/
Collection<ObjectNode> getCollection(String propertyName) {
Collection<ObjectNode> result = null;
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
result = new ArrayList<ObjectNode>();
for (JsonNode n : this.propertyBag.findValues(propertyName)) {
result.add((ObjectNode) n);
}
}
return result;
}
/**
* Gets the value of a property identified by an array of property names that forms the path.
*
* @param propertyNames that form the path to the property to get.
* @return the value of the property.
*/
public Object getObjectByPath(List<String> propertyNames) {
ObjectNode propBag = this.propertyBag;
JsonNode value = null;
String propertyName = null;
int matchedProperties = 0;
Iterator<String> iterator = propertyNames.iterator();
if (iterator.hasNext()) {
do {
propertyName = iterator.next();
if (propBag.has(propertyName)) {
matchedProperties++;
value = propBag.get(propertyName);
if (!value.isObject()) {
break;
}
propBag = (ObjectNode) value;
} else {
break;
}
} while (iterator.hasNext());
if (value != null && matchedProperties == propertyNames.size()) {
return getValue(value);
}
}
return null;
}
private ObjectNode fromJson(byte[] bytes) {
try {
return (ObjectNode) getMapper().readTree(bytes);
} catch (IOException e) {
throw new IllegalArgumentException(
String.format("Unable to parse JSON %s", Arrays.toString(bytes)), e);
}
}
private ObjectNode fromJson(String json) {
try {
return (ObjectNode) getMapper().readTree(json);
} catch (IOException e) {
throw new IllegalArgumentException(
String.format("Unable to parse JSON %s", json), e);
}
}
private ObjectNode fromJson(ByteBuffer json) {
try {
return (ObjectNode) getMapper().readTree(new ByteBufferBackedInputStream(json));
} catch (IOException e) {
throw new IllegalArgumentException("Unable to parse JSON from ByteBuffer", e);
}
}
/**
* Serialize json to byte buffer byte buffer.
*
* @return the byte buffer
*/
public ByteBuffer serializeJsonToByteBuffer() {
this.populatePropertyBag();
return Utils.serializeJsonToByteBuffer(getMapper(), propertyBag);
}
public ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper) {
this.populatePropertyBag();
return Utils.serializeJsonToByteBuffer(objectMapper, propertyBag);
}
private String toJson(Object object) {
try {
return getMapper().writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to convert JSON to STRING", e);
}
}
private String toPrettyJson(Object object) {
try {
return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to convert JSON to STRING", e);
}
}
/**
* Converts to an Object (only POJOs and JsonNode are supported).
*
* @param <T> the type of the object.
* @param c the class of the object, either a POJO class or JsonNode. If c is a POJO class, it must be a member
* (and not an anonymous or local) and a static one.
* @return the POJO.
* @throws IllegalArgumentException thrown if an error occurs
* @throws IllegalStateException thrown when objectmapper is unable to read tree
*/
@SuppressWarnings("unchecked")
public <T> T toObject(Class<T> c) {
if (InternalObjectNode.class.isAssignableFrom(c)) {
return (T) new InternalObjectNode(this.propertyBag);
}
if (JsonSerializable.class.isAssignableFrom(c)
|| String.class.isAssignableFrom(c)
|| Number.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c)
|| containsJsonSerializable(c)) {
return c.cast(this.get(Constants.Properties.VALUE));
}
if (List.class.isAssignableFrom(c)) {
Object o = this.get(Constants.Properties.VALUE);
try {
return this.getMapper().readValue(o.toString(), c);
} catch (IOException e) {
throw new IllegalStateException("Failed to convert to collection.", e);
}
}
if (JsonNode.class.isAssignableFrom(c) || ObjectNode.class.isAssignableFrom(c)) {
if (JsonNode.class != c) {
if (ObjectNode.class != c) {
throw new IllegalArgumentException(
"We support JsonNode but not its sub-classes.");
}
}
return c.cast(this.propertyBag);
} else {
JsonSerializable.checkForValidPOJO(c);
try {
return this.getMapper().treeToValue(propertyBag, c);
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
/**
* Converts to a JSON string.
*
* @return the JSON string.
*/
public String toJson() {
return this.toJson(SerializationFormattingPolicy.NONE);
}
/**
* Converts to a JSON string.
*
* @param formattingPolicy the formatting policy to be used.
* @return the JSON string.
*/
protected String toJson(SerializationFormattingPolicy formattingPolicy) {
this.populatePropertyBag();
if (SerializationFormattingPolicy.INDENTED.equals(formattingPolicy)) {
return toPrettyJson(propertyBag);
} else {
return toJson(propertyBag);
}
}
/**
* Gets Simple STRING representation of property bag.
* <p>
* For proper conversion to json and inclusion of the default values
* use {@link
*
* @return string representation of property bag.
*/
public String toString() {
return toJson(propertyBag);
}
public ObjectNode getPropertyBag() {
return this.propertyBag;
}
<T> boolean containsJsonSerializable(Class<T> c) {
return CompositePath.class.equals(c)
|| ConflictResolutionPolicy.class.equals(c)
|| ChangeFeedPolicy.class.equals(c)
|| ExcludedPath.class.equals(c)
|| IncludedPath.class.equals(c)
|| IndexingPolicy.class.equals(c)
|| PartitionKeyDefinition.class.equals(c)
|| SpatialSpec.class.equals(c)
|| SqlParameter.class.equals(c)
|| SqlQuerySpec.class.equals(c)
|| UniqueKey.class.equals(c)
|| UniqueKeyPolicy.class.equals(c);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JsonSerializable that = (JsonSerializable) o;
return Objects.equals(propertyBag, that.propertyBag);
}
@Override
public int hashCode() {
return Objects.hash(propertyBag);
}
} | class JsonSerializable {
private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper();
private static final Logger LOGGER = LoggerFactory.getLogger(JsonSerializable.class);
transient ObjectNode propertyBag = null;
private ObjectMapper om;
public JsonSerializable() {
this.propertyBag = OBJECT_MAPPER.createObjectNode();
}
/**
* Constructor.
*
* @param jsonString the json string that represents the JsonSerializable.
* @param objectMapper the custom object mapper
*/
protected JsonSerializable(String jsonString, ObjectMapper objectMapper) {
this.propertyBag = fromJson(jsonString);
this.om = objectMapper;
}
/**
* Constructor.
*
* @param jsonString the json string that represents the JsonSerializable.
*/
public JsonSerializable(String jsonString) {
this.propertyBag = fromJson(jsonString);
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the {@link JsonSerializable}
*/
public JsonSerializable(ObjectNode objectNode) {
this.propertyBag = objectNode;
}
protected JsonSerializable(ByteBuffer byteBuffer) {
this.propertyBag = fromJson(byteBuffer);
}
protected JsonSerializable(byte[] bytes) {
this.propertyBag = fromJson(bytes);
}
private static void checkForValidPOJO(Class<?> c) {
if (c.isAnonymousClass() || c.isLocalClass()) {
throw new IllegalArgumentException(
String.format("%s can't be an anonymous or local class.", c.getName()));
}
if (c.isMemberClass() && !Modifier.isStatic(c.getModifiers())) {
throw new IllegalArgumentException(
String.format("%s must be static if it's a member class.", c.getName()));
}
}
public static Object getValue(JsonNode value) {
if (value.isValueNode()) {
switch (value.getNodeType()) {
case BOOLEAN:
return value.asBoolean();
case NUMBER:
if (value.isInt()) {
return value.asInt();
} else if (value.isLong()) {
return value.asLong();
} else if (value.isDouble()) {
return value.asDouble();
} else {
return value;
}
case STRING:
return value.asText();
default:
return value;
}
}
return value;
}
private ObjectMapper getMapper() {
if (this.om != null) {
return this.om;
}
return OBJECT_MAPPER;
}
void setMapper(ObjectMapper om) {
this.om = om;
}
@JsonIgnore
public Logger getLogger() {
return LOGGER;
}
public void populatePropertyBag() {
}
/**
* Returns the propertybag(JsonNode) in a hashMap
*
* @return the HashMap.
*/
@SuppressWarnings("unchecked")
public Map<String, Object> getMap() {
return getMapper().convertValue(this.propertyBag, HashMap.class);
}
@SuppressWarnings("unchecked")
public <T> Map<String, T> getMap(String propertyKey) {
if (this.propertyBag.has(propertyKey)) {
Object value = this.get(propertyKey);
return (Map<String, T>) getMapper().convertValue(value, HashMap.class);
}
return null;
}
/**
* Checks whether a property exists.
*
* @param propertyName the property to look up.
* @return true if the property exists.
*/
public boolean has(String propertyName) {
return this.propertyBag.has(propertyName);
}
/**
* Removes a value by propertyName.
*
* @param propertyName the property to remove.
*/
public void remove(String propertyName) {
this.propertyBag.remove(propertyName);
}
/**
* Sets the value of a property.
*
* @param <T> the type of the object.
* @param propertyName the property to set.
* @param value the value of the property.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public <T> void set(String propertyName, T value) {
if (value == null) {
this.propertyBag.putNull(propertyName);
} else if (value instanceof Collection) {
ArrayNode jsonArray = propertyBag.arrayNode();
this.internalSetCollection(propertyName, (Collection) value, jsonArray);
this.propertyBag.set(propertyName, jsonArray);
} else if (value instanceof JsonNode) {
this.propertyBag.set(propertyName, (JsonNode) value);
} else if (value instanceof JsonSerializable) {
JsonSerializable castedValue = (JsonSerializable) value;
castedValue.populatePropertyBag();
this.propertyBag.set(propertyName, castedValue.propertyBag);
} else if (containsJsonSerializable(value.getClass())) {
ModelBridgeInternal.populatePropertyBag(value);
this.propertyBag.set(propertyName, ModelBridgeInternal.getJsonSerializable(value).propertyBag);
} else {
this.propertyBag.set(propertyName, getMapper().valueToTree(value));
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
private <T> void internalSetCollection(String propertyName, Collection<T> collection, ArrayNode targetArray) {
for (T childValue : collection) {
if (childValue == null) {
targetArray.addNull();
} else if (childValue instanceof Collection) {
ArrayNode childArray = targetArray.addArray();
this.internalSetCollection(propertyName, (Collection) childValue, childArray);
} else if (childValue instanceof JsonNode) {
targetArray.add((JsonNode) childValue);
} else if (childValue instanceof JsonSerializable) {
JsonSerializable castedValue = (JsonSerializable) childValue;
castedValue.populatePropertyBag();
targetArray.add(castedValue.propertyBag != null ? castedValue.propertyBag
: this.getMapper().createObjectNode());
} else if (containsJsonSerializable(childValue.getClass())) {
ModelBridgeInternal.populatePropertyBag(childValue);
targetArray.add(ModelBridgeInternal.getJsonSerializable(childValue).propertyBag != null ?
ModelBridgeInternal.getJsonSerializable(childValue).propertyBag : this.getMapper().createObjectNode());
} else {
targetArray.add(this.getMapper().valueToTree(childValue));
}
}
}
/**
* Gets a property value as Object.
*
* @param propertyName the property to get.
* @return the value of the property.
*/
public Object get(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return getValue(this.propertyBag.get(propertyName));
} else {
return null;
}
}
/**
* Gets a string value.
*
* @param propertyName the property to get.
* @return the string value.
*/
public String getString(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asText();
} else {
return null;
}
}
/**
* Gets a boolean value.
*
* @param propertyName the property to get.
* @return the boolean value.
*/
@Nullable
public Boolean getBoolean(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asBoolean();
} else {
return null;
}
}
/**
* Gets an integer value.
*
* @param propertyName the property to get.
* @return the boolean value
*/
public Integer getInt(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asInt();
} else {
return null;
}
}
/**
* Gets a long value.
*
* @param propertyName the property to get.
* @return the long value
*/
protected Long getLong(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asLong();
} else {
return null;
}
}
/**
* Gets a double value.
*
* @param propertyName the property to get.
* @return the double value.
*/
public Double getDouble(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asDouble();
} else {
return null;
}
}
/**
* Gets an object value.
*
* @param <T> the type of the object.
* @param propertyName the property to get.
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object value.
* @throws IllegalStateException thrown if an error occurs
*/
@SuppressWarnings("unchecked")
public <T> T getObject(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
JsonNode jsonObj = propertyBag.get(propertyName);
if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c) || Object.class == c) {
return c.cast(getValue(jsonObj));
} else if (Enum.class.isAssignableFrom(c)) {
try {
String value = String.class.cast(getValue(jsonObj));
value = convertFromCamelCase.length > 0 && convertFromCamelCase[0]
? Strings.fromCamelCaseToUpperCase(value) : value;
return c.cast(c.getMethod("valueOf", String.class).invoke(null, value));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException("Failed to create enum.", e);
}
} else if (JsonSerializable.class.isAssignableFrom(c)) {
return (T) instantiateFromObjectNodeAndType((ObjectNode) jsonObj, c);
} else if (containsJsonSerializable(c)) {
return ModelBridgeInternal.instantiateByObjectNode((ObjectNode) jsonObj, c);
}
else {
JsonSerializable.checkForValidPOJO(c);
try {
return this.getMapper().treeToValue(jsonObj, c);
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
return null;
}
/**
* Gets an object List.
*
* @param <T> the type of the objects in the List.
* @param propertyName the property to get
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object collection.
* @throws IllegalStateException thrown if an error occurs
*/
@SuppressWarnings("unchecked")
public <T> List<T> getList(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
JsonNode jsonArray = this.propertyBag.get(propertyName);
ArrayList<T> result = new ArrayList<T>();
boolean isBaseClass = false;
boolean isEnumClass = false;
boolean isJsonSerializable = false;
boolean containsJsonSerializable = false;
if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c) || Object.class == c) {
isBaseClass = true;
} else if (Enum.class.isAssignableFrom(c)) {
isEnumClass = true;
} else if (JsonSerializable.class.isAssignableFrom(c)) {
isJsonSerializable = true;
} else if (containsJsonSerializable(c)) {
containsJsonSerializable = true;
} else {
JsonSerializable.checkForValidPOJO(c);
}
for (JsonNode n : jsonArray) {
if (isBaseClass) {
result.add(c.cast(getValue(n)));
} else if (isEnumClass) {
try {
String value = String.class.cast(getValue(n));
value = convertFromCamelCase.length > 0 && convertFromCamelCase[0]
? Strings.fromCamelCaseToUpperCase(value) : value;
result.add(c.cast(c.getMethod("valueOf", String.class).invoke(null, value)));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException("Failed to create enum.", e);
}
} else if (isJsonSerializable) {
T t = (T) instantiateFromObjectNodeAndType((ObjectNode) n, c);
result.add(t);
} else if (containsJsonSerializable) {
T t = ModelBridgeInternal.instantiateByObjectNode((ObjectNode) n, c);
result.add(t);
} else {
try {
result.add(this.getMapper().treeToValue(n, c));
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
return result;
}
return null;
}
/**
* Gets an object collection.
*
* @param <T> the type of the objects in the collection.
* @param propertyName the property to get
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object collection.
*/
public <T> Collection<T> getCollection(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
return getList(propertyName, c, convertFromCamelCase);
}
/**
* Gets a ObjectNode.
*
* @param propertyName the property to get.
* @return the ObjectNode.
*/
public ObjectNode getObject(String propertyName) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return (ObjectNode) this.propertyBag.get(propertyName);
}
return null;
}
/**
* Gets a ObjectNode collection.
*
* @param propertyName the property to get.
* @return the ObjectNode collection.
*/
Collection<ObjectNode> getCollection(String propertyName) {
Collection<ObjectNode> result = null;
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
result = new ArrayList<ObjectNode>();
for (JsonNode n : this.propertyBag.findValues(propertyName)) {
result.add((ObjectNode) n);
}
}
return result;
}
/**
* Gets the value of a property identified by an array of property names that forms the path.
*
* @param propertyNames that form the path to the property to get.
* @return the value of the property.
*/
public Object getObjectByPath(List<String> propertyNames) {
ObjectNode propBag = this.propertyBag;
JsonNode value = null;
String propertyName = null;
int matchedProperties = 0;
Iterator<String> iterator = propertyNames.iterator();
if (iterator.hasNext()) {
do {
propertyName = iterator.next();
if (propBag.has(propertyName)) {
matchedProperties++;
value = propBag.get(propertyName);
if (!value.isObject()) {
break;
}
propBag = (ObjectNode) value;
} else {
break;
}
} while (iterator.hasNext());
if (value != null && matchedProperties == propertyNames.size()) {
return getValue(value);
}
}
return null;
}
private ObjectNode fromJson(byte[] bytes) {
try {
return (ObjectNode) getMapper().readTree(bytes);
} catch (IOException e) {
throw new IllegalArgumentException(
String.format("Unable to parse JSON %s", Arrays.toString(bytes)), e);
}
}
private ObjectNode fromJson(String json) {
try {
return (ObjectNode) getMapper().readTree(json);
} catch (IOException e) {
throw new IllegalArgumentException(
String.format("Unable to parse JSON %s", json), e);
}
}
private ObjectNode fromJson(ByteBuffer json) {
try {
return (ObjectNode) getMapper().readTree(new ByteBufferBackedInputStream(json));
} catch (IOException e) {
throw new IllegalArgumentException("Unable to parse JSON from ByteBuffer", e);
}
}
/**
* Serialize json to byte buffer byte buffer.
*
* @return the byte buffer
*/
public ByteBuffer serializeJsonToByteBuffer() {
this.populatePropertyBag();
return Utils.serializeJsonToByteBuffer(getMapper(), propertyBag);
}
public ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper) {
this.populatePropertyBag();
return Utils.serializeJsonToByteBuffer(objectMapper, propertyBag);
}
private String toJson(Object object) {
try {
return getMapper().writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to convert JSON to STRING", e);
}
}
private String toPrettyJson(Object object) {
try {
return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to convert JSON to STRING", e);
}
}
/**
* Converts to an Object (only POJOs and JsonNode are supported).
*
* @param <T> the type of the object.
* @param c the class of the object, either a POJO class or JsonNode. If c is a POJO class, it must be a member
* (and not an anonymous or local) and a static one.
* @return the POJO.
* @throws IllegalArgumentException thrown if an error occurs
* @throws IllegalStateException thrown when objectmapper is unable to read tree
*/
@SuppressWarnings("unchecked")
public <T> T toObject(Class<T> c) {
if (InternalObjectNode.class.isAssignableFrom(c)) {
return (T) new InternalObjectNode(this.propertyBag);
}
if (JsonSerializable.class.isAssignableFrom(c)
|| String.class.isAssignableFrom(c)
|| Number.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c)
|| containsJsonSerializable(c)) {
return c.cast(this.get(Constants.Properties.VALUE));
}
if (List.class.isAssignableFrom(c)) {
Object o = this.get(Constants.Properties.VALUE);
try {
return this.getMapper().readValue(o.toString(), c);
} catch (IOException e) {
throw new IllegalStateException("Failed to convert to collection.", e);
}
}
if (JsonNode.class.isAssignableFrom(c) || ObjectNode.class.isAssignableFrom(c)) {
if (JsonNode.class != c) {
if (ObjectNode.class != c) {
throw new IllegalArgumentException(
"We support JsonNode but not its sub-classes.");
}
}
return c.cast(this.propertyBag);
} else {
JsonSerializable.checkForValidPOJO(c);
try {
return this.getMapper().treeToValue(propertyBag, c);
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
/**
* Converts to a JSON string.
*
* @return the JSON string.
*/
public String toJson() {
return this.toJson(SerializationFormattingPolicy.NONE);
}
/**
* Converts to a JSON string.
*
* @param formattingPolicy the formatting policy to be used.
* @return the JSON string.
*/
protected String toJson(SerializationFormattingPolicy formattingPolicy) {
this.populatePropertyBag();
if (SerializationFormattingPolicy.INDENTED.equals(formattingPolicy)) {
return toPrettyJson(propertyBag);
} else {
return toJson(propertyBag);
}
}
/**
* Gets Simple STRING representation of property bag.
* <p>
* For proper conversion to json and inclusion of the default values
* use {@link
*
* @return string representation of property bag.
*/
public String toString() {
return toJson(propertyBag);
}
public ObjectNode getPropertyBag() {
return this.propertyBag;
}
<T> boolean containsJsonSerializable(Class<T> c) {
return CompositePath.class.equals(c)
|| ConflictResolutionPolicy.class.equals(c)
|| ChangeFeedPolicy.class.equals(c)
|| ExcludedPath.class.equals(c)
|| IncludedPath.class.equals(c)
|| IndexingPolicy.class.equals(c)
|| PartitionKeyDefinition.class.equals(c)
|| SpatialSpec.class.equals(c)
|| SqlParameter.class.equals(c)
|| SqlQuerySpec.class.equals(c)
|| UniqueKey.class.equals(c)
|| UniqueKeyPolicy.class.equals(c);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JsonSerializable that = (JsonSerializable) o;
return Objects.equals(propertyBag, that.propertyBag);
}
@Override
public int hashCode() {
return Objects.hash(propertyBag);
}
} |
I will test without this and remove this in a future PR. | public static JsonSerializable instantiateFromObjectNodeAndType(ObjectNode objectNode, Class<?> klassType) {
if (klassType.equals(Document.class)) {
return new Document(objectNode);
}
if (klassType.equals(InternalObjectNode.class)) {
return new InternalObjectNode(objectNode);
}
if (klassType.equals(PartitionKeyRange.class)) {
return new PartitionKeyRange(objectNode);
}
if (klassType.equals(Range.class)) {
return new Range<>(objectNode);
}
if (klassType.equals(QueryInfo.class)) {
return new QueryInfo(objectNode);
}
if (klassType.equals(PartitionedQueryExecutionInfoInternal.class)) {
return new PartitionedQueryExecutionInfoInternal(objectNode);
}
if (klassType.equals(QueryItem.class)) {
return new QueryItem(objectNode);
}
if (klassType.equals(Address.class)) {
return new Address(objectNode);
}
if (klassType.equals(DatabaseAccount.class)) {
return new DatabaseAccount(objectNode);
}
if (klassType.equals(DatabaseAccountLocation.class)) {
return new DatabaseAccountLocation(objectNode);
}
if (klassType.equals(ReplicationPolicy.class)) {
return new ReplicationPolicy(objectNode);
}
if (klassType.equals(ConsistencyPolicy.class)) {
return new ConsistencyPolicy(objectNode);
}
if (klassType.equals(DocumentCollection.class)) {
return new DocumentCollection(objectNode);
}
if (klassType.equals(Database.class)) {
return new Database(objectNode);
} else {
try {
return (JsonSerializable) klassType.getDeclaredConstructor(String.class)
.newInstance(Utils.toJson(Utils.getSimpleObjectMapper(), objectNode));
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
}
} | try { | public static JsonSerializable instantiateFromObjectNodeAndType(ObjectNode objectNode, Class<?> klassType) {
if (klassType.equals(Document.class)) {
return new Document(objectNode);
}
if (klassType.equals(InternalObjectNode.class)) {
return new InternalObjectNode(objectNode);
}
if (klassType.equals(PartitionKeyRange.class)) {
return new PartitionKeyRange(objectNode);
}
if (klassType.equals(Range.class)) {
return new Range<>(objectNode);
}
if (klassType.equals(QueryInfo.class)) {
return new QueryInfo(objectNode);
}
if (klassType.equals(PartitionedQueryExecutionInfoInternal.class)) {
return new PartitionedQueryExecutionInfoInternal(objectNode);
}
if (klassType.equals(QueryItem.class)) {
return new QueryItem(objectNode);
}
if (klassType.equals(Address.class)) {
return new Address(objectNode);
}
if (klassType.equals(DatabaseAccount.class)) {
return new DatabaseAccount(objectNode);
}
if (klassType.equals(DatabaseAccountLocation.class)) {
return new DatabaseAccountLocation(objectNode);
}
if (klassType.equals(ReplicationPolicy.class)) {
return new ReplicationPolicy(objectNode);
}
if (klassType.equals(ConsistencyPolicy.class)) {
return new ConsistencyPolicy(objectNode);
}
if (klassType.equals(DocumentCollection.class)) {
return new DocumentCollection(objectNode);
}
if (klassType.equals(Database.class)) {
return new Database(objectNode);
} else {
try {
return (JsonSerializable) klassType.getDeclaredConstructor(String.class)
.newInstance(Utils.toJson(Utils.getSimpleObjectMapper(), objectNode));
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
}
} | class JsonSerializable {
private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper();
private static final Logger LOGGER = LoggerFactory.getLogger(JsonSerializable.class);
transient ObjectNode propertyBag = null;
private ObjectMapper om;
public JsonSerializable() {
this.propertyBag = OBJECT_MAPPER.createObjectNode();
}
/**
* Constructor.
*
* @param jsonString the json string that represents the JsonSerializable.
* @param objectMapper the custom object mapper
*/
protected JsonSerializable(String jsonString, ObjectMapper objectMapper) {
this.propertyBag = fromJson(jsonString);
this.om = objectMapper;
}
/**
* Constructor.
*
* @param jsonString the json string that represents the JsonSerializable.
*/
public JsonSerializable(String jsonString) {
this.propertyBag = fromJson(jsonString);
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the {@link JsonSerializable}
*/
public JsonSerializable(ObjectNode objectNode) {
this.propertyBag = objectNode;
}
protected JsonSerializable(ByteBuffer byteBuffer) {
this.propertyBag = fromJson(byteBuffer);
}
protected JsonSerializable(byte[] bytes) {
this.propertyBag = fromJson(bytes);
}
private static void checkForValidPOJO(Class<?> c) {
if (c.isAnonymousClass() || c.isLocalClass()) {
throw new IllegalArgumentException(
String.format("%s can't be an anonymous or local class.", c.getName()));
}
if (c.isMemberClass() && !Modifier.isStatic(c.getModifiers())) {
throw new IllegalArgumentException(
String.format("%s must be static if it's a member class.", c.getName()));
}
}
public static Object getValue(JsonNode value) {
if (value.isValueNode()) {
switch (value.getNodeType()) {
case BOOLEAN:
return value.asBoolean();
case NUMBER:
if (value.isInt()) {
return value.asInt();
} else if (value.isLong()) {
return value.asLong();
} else if (value.isDouble()) {
return value.asDouble();
} else {
return value;
}
case STRING:
return value.asText();
default:
return value;
}
}
return value;
}
private ObjectMapper getMapper() {
if (this.om != null) {
return this.om;
}
return OBJECT_MAPPER;
}
void setMapper(ObjectMapper om) {
this.om = om;
}
@JsonIgnore
public Logger getLogger() {
return LOGGER;
}
public void populatePropertyBag() {
}
/**
* Returns the propertybag(JsonNode) in a hashMap
*
* @return the HashMap.
*/
@SuppressWarnings("unchecked")
public Map<String, Object> getMap() {
return getMapper().convertValue(this.propertyBag, HashMap.class);
}
@SuppressWarnings("unchecked")
public <T> Map<String, T> getMap(String propertyKey) {
if (this.propertyBag.has(propertyKey)) {
Object value = this.get(propertyKey);
return (Map<String, T>) getMapper().convertValue(value, HashMap.class);
}
return null;
}
/**
* Checks whether a property exists.
*
* @param propertyName the property to look up.
* @return true if the property exists.
*/
public boolean has(String propertyName) {
return this.propertyBag.has(propertyName);
}
/**
* Removes a value by propertyName.
*
* @param propertyName the property to remove.
*/
public void remove(String propertyName) {
this.propertyBag.remove(propertyName);
}
/**
* Sets the value of a property.
*
* @param <T> the type of the object.
* @param propertyName the property to set.
* @param value the value of the property.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public <T> void set(String propertyName, T value) {
if (value == null) {
this.propertyBag.putNull(propertyName);
} else if (value instanceof Collection) {
ArrayNode jsonArray = propertyBag.arrayNode();
this.internalSetCollection(propertyName, (Collection) value, jsonArray);
this.propertyBag.set(propertyName, jsonArray);
} else if (value instanceof JsonNode) {
this.propertyBag.set(propertyName, (JsonNode) value);
} else if (value instanceof JsonSerializable) {
JsonSerializable castedValue = (JsonSerializable) value;
castedValue.populatePropertyBag();
this.propertyBag.set(propertyName, castedValue.propertyBag);
} else if (containsJsonSerializable(value.getClass())) {
ModelBridgeInternal.populatePropertyBag(value);
this.propertyBag.set(propertyName, ModelBridgeInternal.getJsonSerializable(value).propertyBag);
} else {
this.propertyBag.set(propertyName, getMapper().valueToTree(value));
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
private <T> void internalSetCollection(String propertyName, Collection<T> collection, ArrayNode targetArray) {
for (T childValue : collection) {
if (childValue == null) {
targetArray.addNull();
} else if (childValue instanceof Collection) {
ArrayNode childArray = targetArray.addArray();
this.internalSetCollection(propertyName, (Collection) childValue, childArray);
} else if (childValue instanceof JsonNode) {
targetArray.add((JsonNode) childValue);
} else if (childValue instanceof JsonSerializable) {
JsonSerializable castedValue = (JsonSerializable) childValue;
castedValue.populatePropertyBag();
targetArray.add(castedValue.propertyBag != null ? castedValue.propertyBag
: this.getMapper().createObjectNode());
} else if (containsJsonSerializable(childValue.getClass())) {
ModelBridgeInternal.populatePropertyBag(childValue);
targetArray.add(ModelBridgeInternal.getJsonSerializable(childValue).propertyBag != null ?
ModelBridgeInternal.getJsonSerializable(childValue).propertyBag : this.getMapper().createObjectNode());
} else {
targetArray.add(this.getMapper().valueToTree(childValue));
}
}
}
/**
* Gets a property value as Object.
*
* @param propertyName the property to get.
* @return the value of the property.
*/
public Object get(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return getValue(this.propertyBag.get(propertyName));
} else {
return null;
}
}
/**
* Gets a string value.
*
* @param propertyName the property to get.
* @return the string value.
*/
public String getString(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asText();
} else {
return null;
}
}
/**
* Gets a boolean value.
*
* @param propertyName the property to get.
* @return the boolean value.
*/
@Nullable
public Boolean getBoolean(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asBoolean();
} else {
return null;
}
}
/**
* Gets an integer value.
*
* @param propertyName the property to get.
* @return the boolean value
*/
public Integer getInt(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asInt();
} else {
return null;
}
}
/**
* Gets a long value.
*
* @param propertyName the property to get.
* @return the long value
*/
protected Long getLong(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asLong();
} else {
return null;
}
}
/**
* Gets a double value.
*
* @param propertyName the property to get.
* @return the double value.
*/
public Double getDouble(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asDouble();
} else {
return null;
}
}
/**
* Gets an object value.
*
* @param <T> the type of the object.
* @param propertyName the property to get.
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object value.
* @throws IllegalStateException thrown if an error occurs
*/
@SuppressWarnings("unchecked")
public <T> T getObject(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
JsonNode jsonObj = propertyBag.get(propertyName);
if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c) || Object.class == c) {
return c.cast(getValue(jsonObj));
} else if (Enum.class.isAssignableFrom(c)) {
try {
String value = String.class.cast(getValue(jsonObj));
value = convertFromCamelCase.length > 0 && convertFromCamelCase[0]
? Strings.fromCamelCaseToUpperCase(value) : value;
return c.cast(c.getMethod("valueOf", String.class).invoke(null, value));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException("Failed to create enum.", e);
}
} else if (JsonSerializable.class.isAssignableFrom(c)) {
return (T) instantiateFromObjectNodeAndType((ObjectNode) jsonObj, c);
} else if (containsJsonSerializable(c)) {
return ModelBridgeInternal.instantiateByObjectNode((ObjectNode) jsonObj, c);
}
else {
JsonSerializable.checkForValidPOJO(c);
try {
return this.getMapper().treeToValue(jsonObj, c);
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
return null;
}
/**
* Gets an object List.
*
* @param <T> the type of the objects in the List.
* @param propertyName the property to get
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object collection.
* @throws IllegalStateException thrown if an error occurs
*/
@SuppressWarnings("unchecked")
public <T> List<T> getList(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
JsonNode jsonArray = this.propertyBag.get(propertyName);
ArrayList<T> result = new ArrayList<T>();
boolean isBaseClass = false;
boolean isEnumClass = false;
boolean isJsonSerializable = false;
boolean containsJsonSerializable = false;
if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c) || Object.class == c) {
isBaseClass = true;
} else if (Enum.class.isAssignableFrom(c)) {
isEnumClass = true;
} else if (JsonSerializable.class.isAssignableFrom(c)) {
isJsonSerializable = true;
} else if (containsJsonSerializable(c)) {
containsJsonSerializable = true;
} else {
JsonSerializable.checkForValidPOJO(c);
}
for (JsonNode n : jsonArray) {
if (isBaseClass) {
result.add(c.cast(getValue(n)));
} else if (isEnumClass) {
try {
String value = String.class.cast(getValue(n));
value = convertFromCamelCase.length > 0 && convertFromCamelCase[0]
? Strings.fromCamelCaseToUpperCase(value) : value;
result.add(c.cast(c.getMethod("valueOf", String.class).invoke(null, value)));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException("Failed to create enum.", e);
}
} else if (isJsonSerializable) {
T t = (T) instantiateFromObjectNodeAndType((ObjectNode) n, c);
result.add(t);
} else if (containsJsonSerializable) {
T t = ModelBridgeInternal.instantiateByObjectNode((ObjectNode) n, c);
result.add(t);
} else {
try {
result.add(this.getMapper().treeToValue(n, c));
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
return result;
}
return null;
}
/**
* Gets an object collection.
*
* @param <T> the type of the objects in the collection.
* @param propertyName the property to get
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object collection.
*/
public <T> Collection<T> getCollection(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
return getList(propertyName, c, convertFromCamelCase);
}
/**
* Gets a ObjectNode.
*
* @param propertyName the property to get.
* @return the ObjectNode.
*/
public ObjectNode getObject(String propertyName) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return (ObjectNode) this.propertyBag.get(propertyName);
}
return null;
}
/**
* Gets a ObjectNode collection.
*
* @param propertyName the property to get.
* @return the ObjectNode collection.
*/
Collection<ObjectNode> getCollection(String propertyName) {
Collection<ObjectNode> result = null;
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
result = new ArrayList<ObjectNode>();
for (JsonNode n : this.propertyBag.findValues(propertyName)) {
result.add((ObjectNode) n);
}
}
return result;
}
/**
* Gets the value of a property identified by an array of property names that forms the path.
*
* @param propertyNames that form the path to the property to get.
* @return the value of the property.
*/
public Object getObjectByPath(List<String> propertyNames) {
ObjectNode propBag = this.propertyBag;
JsonNode value = null;
String propertyName = null;
int matchedProperties = 0;
Iterator<String> iterator = propertyNames.iterator();
if (iterator.hasNext()) {
do {
propertyName = iterator.next();
if (propBag.has(propertyName)) {
matchedProperties++;
value = propBag.get(propertyName);
if (!value.isObject()) {
break;
}
propBag = (ObjectNode) value;
} else {
break;
}
} while (iterator.hasNext());
if (value != null && matchedProperties == propertyNames.size()) {
return getValue(value);
}
}
return null;
}
private ObjectNode fromJson(byte[] bytes) {
try {
return (ObjectNode) getMapper().readTree(bytes);
} catch (IOException e) {
throw new IllegalArgumentException(
String.format("Unable to parse JSON %s", Arrays.toString(bytes)), e);
}
}
private ObjectNode fromJson(String json) {
try {
return (ObjectNode) getMapper().readTree(json);
} catch (IOException e) {
throw new IllegalArgumentException(
String.format("Unable to parse JSON %s", json), e);
}
}
private ObjectNode fromJson(ByteBuffer json) {
try {
return (ObjectNode) getMapper().readTree(new ByteBufferBackedInputStream(json));
} catch (IOException e) {
throw new IllegalArgumentException("Unable to parse JSON from ByteBuffer", e);
}
}
/**
* Serialize json to byte buffer byte buffer.
*
* @return the byte buffer
*/
public ByteBuffer serializeJsonToByteBuffer() {
this.populatePropertyBag();
return Utils.serializeJsonToByteBuffer(getMapper(), propertyBag);
}
public ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper) {
this.populatePropertyBag();
return Utils.serializeJsonToByteBuffer(objectMapper, propertyBag);
}
private String toJson(Object object) {
try {
return getMapper().writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to convert JSON to STRING", e);
}
}
private String toPrettyJson(Object object) {
try {
return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to convert JSON to STRING", e);
}
}
/**
* Converts to an Object (only POJOs and JsonNode are supported).
*
* @param <T> the type of the object.
* @param c the class of the object, either a POJO class or JsonNode. If c is a POJO class, it must be a member
* (and not an anonymous or local) and a static one.
* @return the POJO.
* @throws IllegalArgumentException thrown if an error occurs
* @throws IllegalStateException thrown when objectmapper is unable to read tree
*/
@SuppressWarnings("unchecked")
public <T> T toObject(Class<T> c) {
if (InternalObjectNode.class.isAssignableFrom(c)) {
return (T) new InternalObjectNode(this.propertyBag);
}
if (JsonSerializable.class.isAssignableFrom(c)
|| String.class.isAssignableFrom(c)
|| Number.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c)
|| containsJsonSerializable(c)) {
return c.cast(this.get(Constants.Properties.VALUE));
}
if (List.class.isAssignableFrom(c)) {
Object o = this.get(Constants.Properties.VALUE);
try {
return this.getMapper().readValue(o.toString(), c);
} catch (IOException e) {
throw new IllegalStateException("Failed to convert to collection.", e);
}
}
if (JsonNode.class.isAssignableFrom(c) || ObjectNode.class.isAssignableFrom(c)) {
if (JsonNode.class != c) {
if (ObjectNode.class != c) {
throw new IllegalArgumentException(
"We support JsonNode but not its sub-classes.");
}
}
return c.cast(this.propertyBag);
} else {
JsonSerializable.checkForValidPOJO(c);
try {
return this.getMapper().treeToValue(propertyBag, c);
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
/**
* Converts to a JSON string.
*
* @return the JSON string.
*/
public String toJson() {
return this.toJson(SerializationFormattingPolicy.NONE);
}
/**
* Converts to a JSON string.
*
* @param formattingPolicy the formatting policy to be used.
* @return the JSON string.
*/
protected String toJson(SerializationFormattingPolicy formattingPolicy) {
this.populatePropertyBag();
if (SerializationFormattingPolicy.INDENTED.equals(formattingPolicy)) {
return toPrettyJson(propertyBag);
} else {
return toJson(propertyBag);
}
}
/**
* Gets Simple STRING representation of property bag.
* <p>
* For proper conversion to json and inclusion of the default values
* use {@link
*
* @return string representation of property bag.
*/
public String toString() {
return toJson(propertyBag);
}
public ObjectNode getPropertyBag() {
return this.propertyBag;
}
<T> boolean containsJsonSerializable(Class<T> c) {
return CompositePath.class.equals(c)
|| ConflictResolutionPolicy.class.equals(c)
|| ChangeFeedPolicy.class.equals(c)
|| ExcludedPath.class.equals(c)
|| IncludedPath.class.equals(c)
|| IndexingPolicy.class.equals(c)
|| PartitionKeyDefinition.class.equals(c)
|| SpatialSpec.class.equals(c)
|| SqlParameter.class.equals(c)
|| SqlQuerySpec.class.equals(c)
|| UniqueKey.class.equals(c)
|| UniqueKeyPolicy.class.equals(c);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JsonSerializable that = (JsonSerializable) o;
return Objects.equals(propertyBag, that.propertyBag);
}
@Override
public int hashCode() {
return Objects.hash(propertyBag);
}
} | class JsonSerializable {
private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper();
private static final Logger LOGGER = LoggerFactory.getLogger(JsonSerializable.class);
transient ObjectNode propertyBag = null;
private ObjectMapper om;
public JsonSerializable() {
this.propertyBag = OBJECT_MAPPER.createObjectNode();
}
/**
* Constructor.
*
* @param jsonString the json string that represents the JsonSerializable.
* @param objectMapper the custom object mapper
*/
protected JsonSerializable(String jsonString, ObjectMapper objectMapper) {
this.propertyBag = fromJson(jsonString);
this.om = objectMapper;
}
/**
* Constructor.
*
* @param jsonString the json string that represents the JsonSerializable.
*/
public JsonSerializable(String jsonString) {
this.propertyBag = fromJson(jsonString);
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the {@link JsonSerializable}
*/
public JsonSerializable(ObjectNode objectNode) {
this.propertyBag = objectNode;
}
protected JsonSerializable(ByteBuffer byteBuffer) {
this.propertyBag = fromJson(byteBuffer);
}
protected JsonSerializable(byte[] bytes) {
this.propertyBag = fromJson(bytes);
}
private static void checkForValidPOJO(Class<?> c) {
if (c.isAnonymousClass() || c.isLocalClass()) {
throw new IllegalArgumentException(
String.format("%s can't be an anonymous or local class.", c.getName()));
}
if (c.isMemberClass() && !Modifier.isStatic(c.getModifiers())) {
throw new IllegalArgumentException(
String.format("%s must be static if it's a member class.", c.getName()));
}
}
public static Object getValue(JsonNode value) {
if (value.isValueNode()) {
switch (value.getNodeType()) {
case BOOLEAN:
return value.asBoolean();
case NUMBER:
if (value.isInt()) {
return value.asInt();
} else if (value.isLong()) {
return value.asLong();
} else if (value.isDouble()) {
return value.asDouble();
} else {
return value;
}
case STRING:
return value.asText();
default:
return value;
}
}
return value;
}
private ObjectMapper getMapper() {
if (this.om != null) {
return this.om;
}
return OBJECT_MAPPER;
}
void setMapper(ObjectMapper om) {
this.om = om;
}
@JsonIgnore
public Logger getLogger() {
return LOGGER;
}
public void populatePropertyBag() {
}
/**
* Returns the propertybag(JsonNode) in a hashMap
*
* @return the HashMap.
*/
@SuppressWarnings("unchecked")
public Map<String, Object> getMap() {
return getMapper().convertValue(this.propertyBag, HashMap.class);
}
@SuppressWarnings("unchecked")
public <T> Map<String, T> getMap(String propertyKey) {
if (this.propertyBag.has(propertyKey)) {
Object value = this.get(propertyKey);
return (Map<String, T>) getMapper().convertValue(value, HashMap.class);
}
return null;
}
/**
* Checks whether a property exists.
*
* @param propertyName the property to look up.
* @return true if the property exists.
*/
public boolean has(String propertyName) {
return this.propertyBag.has(propertyName);
}
/**
* Removes a value by propertyName.
*
* @param propertyName the property to remove.
*/
public void remove(String propertyName) {
this.propertyBag.remove(propertyName);
}
/**
* Sets the value of a property.
*
* @param <T> the type of the object.
* @param propertyName the property to set.
* @param value the value of the property.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public <T> void set(String propertyName, T value) {
if (value == null) {
this.propertyBag.putNull(propertyName);
} else if (value instanceof Collection) {
ArrayNode jsonArray = propertyBag.arrayNode();
this.internalSetCollection(propertyName, (Collection) value, jsonArray);
this.propertyBag.set(propertyName, jsonArray);
} else if (value instanceof JsonNode) {
this.propertyBag.set(propertyName, (JsonNode) value);
} else if (value instanceof JsonSerializable) {
JsonSerializable castedValue = (JsonSerializable) value;
castedValue.populatePropertyBag();
this.propertyBag.set(propertyName, castedValue.propertyBag);
} else if (containsJsonSerializable(value.getClass())) {
ModelBridgeInternal.populatePropertyBag(value);
this.propertyBag.set(propertyName, ModelBridgeInternal.getJsonSerializable(value).propertyBag);
} else {
this.propertyBag.set(propertyName, getMapper().valueToTree(value));
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
private <T> void internalSetCollection(String propertyName, Collection<T> collection, ArrayNode targetArray) {
for (T childValue : collection) {
if (childValue == null) {
targetArray.addNull();
} else if (childValue instanceof Collection) {
ArrayNode childArray = targetArray.addArray();
this.internalSetCollection(propertyName, (Collection) childValue, childArray);
} else if (childValue instanceof JsonNode) {
targetArray.add((JsonNode) childValue);
} else if (childValue instanceof JsonSerializable) {
JsonSerializable castedValue = (JsonSerializable) childValue;
castedValue.populatePropertyBag();
targetArray.add(castedValue.propertyBag != null ? castedValue.propertyBag
: this.getMapper().createObjectNode());
} else if (containsJsonSerializable(childValue.getClass())) {
ModelBridgeInternal.populatePropertyBag(childValue);
targetArray.add(ModelBridgeInternal.getJsonSerializable(childValue).propertyBag != null ?
ModelBridgeInternal.getJsonSerializable(childValue).propertyBag : this.getMapper().createObjectNode());
} else {
targetArray.add(this.getMapper().valueToTree(childValue));
}
}
}
/**
* Gets a property value as Object.
*
* @param propertyName the property to get.
* @return the value of the property.
*/
public Object get(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return getValue(this.propertyBag.get(propertyName));
} else {
return null;
}
}
/**
* Gets a string value.
*
* @param propertyName the property to get.
* @return the string value.
*/
public String getString(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asText();
} else {
return null;
}
}
/**
* Gets a boolean value.
*
* @param propertyName the property to get.
* @return the boolean value.
*/
@Nullable
public Boolean getBoolean(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asBoolean();
} else {
return null;
}
}
/**
* Gets an integer value.
*
* @param propertyName the property to get.
* @return the boolean value
*/
public Integer getInt(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asInt();
} else {
return null;
}
}
/**
* Gets a long value.
*
* @param propertyName the property to get.
* @return the long value
*/
protected Long getLong(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asLong();
} else {
return null;
}
}
/**
* Gets a double value.
*
* @param propertyName the property to get.
* @return the double value.
*/
public Double getDouble(String propertyName) {
if (this.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return this.propertyBag.get(propertyName).asDouble();
} else {
return null;
}
}
/**
* Gets an object value.
*
* @param <T> the type of the object.
* @param propertyName the property to get.
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object value.
* @throws IllegalStateException thrown if an error occurs
*/
@SuppressWarnings("unchecked")
public <T> T getObject(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
JsonNode jsonObj = propertyBag.get(propertyName);
if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c) || Object.class == c) {
return c.cast(getValue(jsonObj));
} else if (Enum.class.isAssignableFrom(c)) {
try {
String value = String.class.cast(getValue(jsonObj));
value = convertFromCamelCase.length > 0 && convertFromCamelCase[0]
? Strings.fromCamelCaseToUpperCase(value) : value;
return c.cast(c.getMethod("valueOf", String.class).invoke(null, value));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException("Failed to create enum.", e);
}
} else if (JsonSerializable.class.isAssignableFrom(c)) {
return (T) instantiateFromObjectNodeAndType((ObjectNode) jsonObj, c);
} else if (containsJsonSerializable(c)) {
return ModelBridgeInternal.instantiateByObjectNode((ObjectNode) jsonObj, c);
}
else {
JsonSerializable.checkForValidPOJO(c);
try {
return this.getMapper().treeToValue(jsonObj, c);
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
return null;
}
/**
* Gets an object List.
*
* @param <T> the type of the objects in the List.
* @param propertyName the property to get
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object collection.
* @throws IllegalStateException thrown if an error occurs
*/
@SuppressWarnings("unchecked")
public <T> List<T> getList(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
JsonNode jsonArray = this.propertyBag.get(propertyName);
ArrayList<T> result = new ArrayList<T>();
boolean isBaseClass = false;
boolean isEnumClass = false;
boolean isJsonSerializable = false;
boolean containsJsonSerializable = false;
if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c) || Object.class == c) {
isBaseClass = true;
} else if (Enum.class.isAssignableFrom(c)) {
isEnumClass = true;
} else if (JsonSerializable.class.isAssignableFrom(c)) {
isJsonSerializable = true;
} else if (containsJsonSerializable(c)) {
containsJsonSerializable = true;
} else {
JsonSerializable.checkForValidPOJO(c);
}
for (JsonNode n : jsonArray) {
if (isBaseClass) {
result.add(c.cast(getValue(n)));
} else if (isEnumClass) {
try {
String value = String.class.cast(getValue(n));
value = convertFromCamelCase.length > 0 && convertFromCamelCase[0]
? Strings.fromCamelCaseToUpperCase(value) : value;
result.add(c.cast(c.getMethod("valueOf", String.class).invoke(null, value)));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException("Failed to create enum.", e);
}
} else if (isJsonSerializable) {
T t = (T) instantiateFromObjectNodeAndType((ObjectNode) n, c);
result.add(t);
} else if (containsJsonSerializable) {
T t = ModelBridgeInternal.instantiateByObjectNode((ObjectNode) n, c);
result.add(t);
} else {
try {
result.add(this.getMapper().treeToValue(n, c));
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
return result;
}
return null;
}
/**
* Gets an object collection.
*
* @param <T> the type of the objects in the collection.
* @param propertyName the property to get
* @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local)
* and a static one.
* @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case
* separated by underscore,
* before converting to required class.
* @return the object collection.
*/
public <T> Collection<T> getCollection(String propertyName, Class<T> c, boolean... convertFromCamelCase) {
return getList(propertyName, c, convertFromCamelCase);
}
/**
* Gets a ObjectNode.
*
* @param propertyName the property to get.
* @return the ObjectNode.
*/
public ObjectNode getObject(String propertyName) {
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
return (ObjectNode) this.propertyBag.get(propertyName);
}
return null;
}
/**
* Gets a ObjectNode collection.
*
* @param propertyName the property to get.
* @return the ObjectNode collection.
*/
Collection<ObjectNode> getCollection(String propertyName) {
Collection<ObjectNode> result = null;
if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) {
result = new ArrayList<ObjectNode>();
for (JsonNode n : this.propertyBag.findValues(propertyName)) {
result.add((ObjectNode) n);
}
}
return result;
}
/**
* Gets the value of a property identified by an array of property names that forms the path.
*
* @param propertyNames that form the path to the property to get.
* @return the value of the property.
*/
public Object getObjectByPath(List<String> propertyNames) {
ObjectNode propBag = this.propertyBag;
JsonNode value = null;
String propertyName = null;
int matchedProperties = 0;
Iterator<String> iterator = propertyNames.iterator();
if (iterator.hasNext()) {
do {
propertyName = iterator.next();
if (propBag.has(propertyName)) {
matchedProperties++;
value = propBag.get(propertyName);
if (!value.isObject()) {
break;
}
propBag = (ObjectNode) value;
} else {
break;
}
} while (iterator.hasNext());
if (value != null && matchedProperties == propertyNames.size()) {
return getValue(value);
}
}
return null;
}
private ObjectNode fromJson(byte[] bytes) {
try {
return (ObjectNode) getMapper().readTree(bytes);
} catch (IOException e) {
throw new IllegalArgumentException(
String.format("Unable to parse JSON %s", Arrays.toString(bytes)), e);
}
}
private ObjectNode fromJson(String json) {
try {
return (ObjectNode) getMapper().readTree(json);
} catch (IOException e) {
throw new IllegalArgumentException(
String.format("Unable to parse JSON %s", json), e);
}
}
private ObjectNode fromJson(ByteBuffer json) {
try {
return (ObjectNode) getMapper().readTree(new ByteBufferBackedInputStream(json));
} catch (IOException e) {
throw new IllegalArgumentException("Unable to parse JSON from ByteBuffer", e);
}
}
/**
* Serialize json to byte buffer byte buffer.
*
* @return the byte buffer
*/
public ByteBuffer serializeJsonToByteBuffer() {
this.populatePropertyBag();
return Utils.serializeJsonToByteBuffer(getMapper(), propertyBag);
}
public ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper) {
this.populatePropertyBag();
return Utils.serializeJsonToByteBuffer(objectMapper, propertyBag);
}
private String toJson(Object object) {
try {
return getMapper().writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to convert JSON to STRING", e);
}
}
private String toPrettyJson(Object object) {
try {
return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to convert JSON to STRING", e);
}
}
/**
* Converts to an Object (only POJOs and JsonNode are supported).
*
* @param <T> the type of the object.
* @param c the class of the object, either a POJO class or JsonNode. If c is a POJO class, it must be a member
* (and not an anonymous or local) and a static one.
* @return the POJO.
* @throws IllegalArgumentException thrown if an error occurs
* @throws IllegalStateException thrown when objectmapper is unable to read tree
*/
@SuppressWarnings("unchecked")
public <T> T toObject(Class<T> c) {
if (InternalObjectNode.class.isAssignableFrom(c)) {
return (T) new InternalObjectNode(this.propertyBag);
}
if (JsonSerializable.class.isAssignableFrom(c)
|| String.class.isAssignableFrom(c)
|| Number.class.isAssignableFrom(c)
|| Boolean.class.isAssignableFrom(c)
|| containsJsonSerializable(c)) {
return c.cast(this.get(Constants.Properties.VALUE));
}
if (List.class.isAssignableFrom(c)) {
Object o = this.get(Constants.Properties.VALUE);
try {
return this.getMapper().readValue(o.toString(), c);
} catch (IOException e) {
throw new IllegalStateException("Failed to convert to collection.", e);
}
}
if (JsonNode.class.isAssignableFrom(c) || ObjectNode.class.isAssignableFrom(c)) {
if (JsonNode.class != c) {
if (ObjectNode.class != c) {
throw new IllegalArgumentException(
"We support JsonNode but not its sub-classes.");
}
}
return c.cast(this.propertyBag);
} else {
JsonSerializable.checkForValidPOJO(c);
try {
return this.getMapper().treeToValue(propertyBag, c);
} catch (IOException e) {
throw new IllegalStateException("Failed to get POJO.", e);
}
}
}
/**
* Converts to a JSON string.
*
* @return the JSON string.
*/
public String toJson() {
return this.toJson(SerializationFormattingPolicy.NONE);
}
/**
* Converts to a JSON string.
*
* @param formattingPolicy the formatting policy to be used.
* @return the JSON string.
*/
protected String toJson(SerializationFormattingPolicy formattingPolicy) {
this.populatePropertyBag();
if (SerializationFormattingPolicy.INDENTED.equals(formattingPolicy)) {
return toPrettyJson(propertyBag);
} else {
return toJson(propertyBag);
}
}
/**
* Gets Simple STRING representation of property bag.
* <p>
* For proper conversion to json and inclusion of the default values
* use {@link
*
* @return string representation of property bag.
*/
public String toString() {
return toJson(propertyBag);
}
public ObjectNode getPropertyBag() {
return this.propertyBag;
}
<T> boolean containsJsonSerializable(Class<T> c) {
return CompositePath.class.equals(c)
|| ConflictResolutionPolicy.class.equals(c)
|| ChangeFeedPolicy.class.equals(c)
|| ExcludedPath.class.equals(c)
|| IncludedPath.class.equals(c)
|| IndexingPolicy.class.equals(c)
|| PartitionKeyDefinition.class.equals(c)
|| SpatialSpec.class.equals(c)
|| SqlParameter.class.equals(c)
|| SqlQuerySpec.class.equals(c)
|| UniqueKey.class.equals(c)
|| UniqueKeyPolicy.class.equals(c);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JsonSerializable that = (JsonSerializable) o;
return Objects.equals(propertyBag, that.propertyBag);
}
@Override
public int hashCode() {
return Objects.hash(propertyBag);
}
} |
Due to the `block()`, do we need to provide `checkExistenceByIdAsync` and `BeginDeleteByIdAsync`? | public boolean checkExistenceById(String id) {
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.checkExistenceById(id, apiVersion);
} | return this.checkExistenceById(id, apiVersion); | public boolean checkExistenceById(String id) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.checkExistenceById(id, apiVersion);
} | class GenericResourcesImpl
extends GroupableResourcesImpl<
GenericResource,
GenericResourceImpl,
GenericResourceInner,
ResourcesClient,
ResourceManager>
implements GenericResources {
private final ClientLogger logger = new ClientLogger(getClass());
public GenericResourcesImpl(ResourceManager resourceManager) {
super(resourceManager.serviceClient().getResources(), resourceManager);
}
@Override
public PagedIterable<GenericResource> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedIterable<GenericResource> listByResourceGroup(String groupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(groupName));
}
@Override
public PagedIterable<GenericResource> listByTag(String resourceGroupName, String tagName, String tagValue) {
return new PagedIterable<>(this.listByTagAsync(resourceGroupName, tagName, tagValue));
}
@Override
public PagedFlux<GenericResource> listByTagAsync(String resourceGroupName, String tagName, String tagValue) {
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName,
ResourceManagerUtils.createOdataFilterForTags(tagName, tagValue), null, null),
res -> (GenericResourceInner) res));
}
@Override
public GenericResource.DefinitionStages.Blank define(String name) {
return new GenericResourceImpl(
name,
new GenericResourceInner(),
this.manager());
}
@Override
public boolean checkExistence(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().checkExistence(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
}
@Override
@Override
public boolean checkExistenceById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().checkExistenceById(id, apiVersion);
}
@Override
public GenericResource getById(String id) {
return this.getByIdAsync(id).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id) {
return this.getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.getByIdAsync(id, apiVersion));
}
@Override
public GenericResource getById(String id, String apiVersion) {
return this.getByIdAsync(id, apiVersion).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().getByIdAsync(id, apiVersion)
.map(this::wrapModel)
.map(r -> r.withApiVersion(apiVersion));
}
@Override
public Mono<Void> deleteByIdAsync(final String id) {
return getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.deleteByIdAsync(id, apiVersion));
}
@Override
public void deleteById(String id, String apiVersion) {
this.deleteByIdAsync(id, apiVersion).block();
}
@Override
public Mono<Void> deleteByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().deleteByIdAsync(id, apiVersion);
}
@Override
public GenericResource get(
String resourceGroupName,
String providerNamespace,
String resourceType,
String name) {
PagedIterable<GenericResource> genericResources = this.listByResourceGroup(resourceGroupName);
for (GenericResource resource : genericResources) {
if (resource.name().equalsIgnoreCase(name)
&& resource.resourceProviderNamespace().equalsIgnoreCase(providerNamespace)
&& resource.resourceType().equalsIgnoreCase(resourceType)) {
return resource;
}
}
return null;
}
@Override
public GenericResource get(
String resourceGroupName,
String resourceProviderNamespace,
String parentResourcePath,
String resourceType,
String resourceName,
String apiVersion) {
if (parentResourcePath == null) {
parentResourcePath = "";
}
GenericResourceInner inner = this.inner().get(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
GenericResourceImpl resource = new GenericResourceImpl(
resourceName,
inner,
this.manager());
return resource.withExistingResourceGroup(resourceGroupName)
.withProviderNamespace(resourceProviderNamespace)
.withParentResourcePath(parentResourcePath)
.withResourceType(resourceType)
.withApiVersion(apiVersion);
}
@Override
public void moveResources(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
this.moveResourcesAsync(sourceResourceGroupName, targetResourceGroup, resources).block();
}
@Override
public Mono<Void> moveResourcesAsync(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
ResourcesMoveInfo moveInfo = new ResourcesMoveInfo();
moveInfo.withTargetResourceGroup(targetResourceGroup.id());
moveInfo.withResources(resources);
return this.inner().moveResourcesAsync(sourceResourceGroupName, moveInfo);
}
public void delete(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion).block();
}
@Override
public Mono<Void> deleteAsync(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion);
}
@Override
protected GenericResourceImpl wrapModel(String id) {
return new GenericResourceImpl(id, new GenericResourceInner(), this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(id))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(id))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(id))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(id));
}
@Override
protected GenericResourceImpl wrapModel(GenericResourceInner inner) {
if (inner == null) {
return null;
}
return new GenericResourceImpl(inner.id(), inner, this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(inner.id()))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(inner.id()))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(inner.id()))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(inner.id()));
}
@Override
public Mono<GenericResourceInner> getInnerAsync(String groupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Get just by resource group and name is not supported. Please use other overloads."));
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Delete just by resource group and name is not supported. Please use other overloads."));
}
@Override
public Accepted<Void> beginDeleteById(String id) {
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.beginDeleteById(id, apiVersion);
}
@Override
public Accepted<Void> beginDeleteById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return AcceptedImpl.newAccepted(logger,
this.manager().serviceClient().getHttpPipeline(),
this.manager().serviceClient().getDefaultPollInterval(),
() -> this.inner().deleteByIdWithResponseAsync(id, apiVersion).block(),
Function.identity(),
Void.class,
null);
}
private Mono<String> getApiVersionFromIdAsync(final String id) {
return this.manager().providers().getByNameAsync(ResourceUtils.resourceProviderFromResourceId(id))
.map(provider -> ResourceUtils.defaultApiVersion(id, provider));
}
@Override
public PagedFlux<GenericResource> listAsync() {
return wrapPageAsync(PagedConverter.mapPage(this.inner().listAsync(),
res -> (GenericResourceInner) res));
}
@Override
public PagedFlux<GenericResource> listByResourceGroupAsync(String resourceGroupName) {
if (CoreUtils.isNullOrEmpty(resourceGroupName)) {
return new PagedFlux<>(() -> Mono.error(
new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")));
}
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName),
res -> (GenericResourceInner) res));
}
} | class GenericResourcesImpl
extends GroupableResourcesImpl<
GenericResource,
GenericResourceImpl,
GenericResourceInner,
ResourcesClient,
ResourceManager>
implements GenericResources {
private final ClientLogger logger = new ClientLogger(getClass());
public GenericResourcesImpl(ResourceManager resourceManager) {
super(resourceManager.serviceClient().getResources(), resourceManager);
}
@Override
public PagedIterable<GenericResource> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedIterable<GenericResource> listByResourceGroup(String groupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(groupName));
}
@Override
public PagedIterable<GenericResource> listByTag(String resourceGroupName, String tagName, String tagValue) {
return new PagedIterable<>(this.listByTagAsync(resourceGroupName, tagName, tagValue));
}
@Override
public PagedFlux<GenericResource> listByTagAsync(String resourceGroupName, String tagName, String tagValue) {
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName,
ResourceManagerUtils.createOdataFilterForTags(tagName, tagValue), null, null),
res -> (GenericResourceInner) res));
}
@Override
public GenericResource.DefinitionStages.Blank define(String name) {
return new GenericResourceImpl(
name,
new GenericResourceInner(),
this.manager());
}
@Override
public boolean checkExistence(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().checkExistence(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
}
@Override
@Override
public boolean checkExistenceById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().checkExistenceById(id, apiVersion);
}
@Override
public GenericResource getById(String id) {
return this.getByIdAsync(id).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
return this.getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.getByIdAsync(id, apiVersion));
}
@Override
public GenericResource getById(String id, String apiVersion) {
return this.getByIdAsync(id, apiVersion).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().getByIdAsync(id, apiVersion)
.map(this::wrapModel)
.map(r -> r.withApiVersion(apiVersion));
}
@Override
public Mono<Void> deleteByIdAsync(final String id) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
return getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.deleteByIdAsync(id, apiVersion));
}
@Override
public void deleteById(String id, String apiVersion) {
this.deleteByIdAsync(id, apiVersion).block();
}
@Override
public Mono<Void> deleteByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().deleteByIdAsync(id, apiVersion);
}
@Override
public GenericResource get(
String resourceGroupName,
String providerNamespace,
String resourceType,
String name) {
PagedIterable<GenericResource> genericResources = this.listByResourceGroup(resourceGroupName);
for (GenericResource resource : genericResources) {
if (resource.name().equalsIgnoreCase(name)
&& resource.resourceProviderNamespace().equalsIgnoreCase(providerNamespace)
&& resource.resourceType().equalsIgnoreCase(resourceType)) {
return resource;
}
}
return null;
}
@Override
public GenericResource get(
String resourceGroupName,
String resourceProviderNamespace,
String parentResourcePath,
String resourceType,
String resourceName,
String apiVersion) {
if (parentResourcePath == null) {
parentResourcePath = "";
}
GenericResourceInner inner = this.inner().get(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
GenericResourceImpl resource = new GenericResourceImpl(
resourceName,
inner,
this.manager());
return resource.withExistingResourceGroup(resourceGroupName)
.withProviderNamespace(resourceProviderNamespace)
.withParentResourcePath(parentResourcePath)
.withResourceType(resourceType)
.withApiVersion(apiVersion);
}
@Override
public void moveResources(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
this.moveResourcesAsync(sourceResourceGroupName, targetResourceGroup, resources).block();
}
@Override
public Mono<Void> moveResourcesAsync(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
ResourcesMoveInfo moveInfo = new ResourcesMoveInfo();
moveInfo.withTargetResourceGroup(targetResourceGroup.id());
moveInfo.withResources(resources);
return this.inner().moveResourcesAsync(sourceResourceGroupName, moveInfo);
}
public void delete(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion).block();
}
@Override
public Mono<Void> deleteAsync(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion);
}
@Override
protected GenericResourceImpl wrapModel(String id) {
return new GenericResourceImpl(id, new GenericResourceInner(), this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(id))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(id))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(id))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(id));
}
@Override
protected GenericResourceImpl wrapModel(GenericResourceInner inner) {
if (inner == null) {
return null;
}
return new GenericResourceImpl(inner.id(), inner, this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(inner.id()))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(inner.id()))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(inner.id()))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(inner.id()));
}
@Override
public Mono<GenericResourceInner> getInnerAsync(String groupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Get just by resource group and name is not supported. Please use other overloads."));
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Delete just by resource group and name is not supported. Please use other overloads."));
}
@Override
public Accepted<Void> beginDeleteById(String id) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.beginDeleteById(id, apiVersion);
}
@Override
public Accepted<Void> beginDeleteById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return AcceptedImpl.newAccepted(logger,
this.manager().serviceClient().getHttpPipeline(),
this.manager().serviceClient().getDefaultPollInterval(),
() -> this.inner().deleteByIdWithResponseAsync(id, apiVersion).block(),
Function.identity(),
Void.class,
null);
}
private Mono<String> getApiVersionFromIdAsync(final String id) {
return this.manager().providers().getByNameAsync(ResourceUtils.resourceProviderFromResourceId(id))
.map(provider -> ResourceUtils.defaultApiVersion(id, provider));
}
@Override
public PagedFlux<GenericResource> listAsync() {
return wrapPageAsync(PagedConverter.mapPage(this.inner().listAsync(),
res -> (GenericResourceInner) res));
}
@Override
public PagedFlux<GenericResource> listByResourceGroupAsync(String resourceGroupName) {
if (CoreUtils.isNullOrEmpty(resourceGroupName)) {
return new PagedFlux<>(() -> Mono.error(
new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")));
}
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName),
res -> (GenericResourceInner) res));
}
} |
`beginDeleteByIdAsync` will not be provided as this is for start of sync polling. No async until required. `checkExistenceByIdAsync` is not there because previously the async version is not there. Any strong opinion to add? | public boolean checkExistenceById(String id) {
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.checkExistenceById(id, apiVersion);
} | return this.checkExistenceById(id, apiVersion); | public boolean checkExistenceById(String id) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.checkExistenceById(id, apiVersion);
} | class GenericResourcesImpl
extends GroupableResourcesImpl<
GenericResource,
GenericResourceImpl,
GenericResourceInner,
ResourcesClient,
ResourceManager>
implements GenericResources {
private final ClientLogger logger = new ClientLogger(getClass());
public GenericResourcesImpl(ResourceManager resourceManager) {
super(resourceManager.serviceClient().getResources(), resourceManager);
}
@Override
public PagedIterable<GenericResource> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedIterable<GenericResource> listByResourceGroup(String groupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(groupName));
}
@Override
public PagedIterable<GenericResource> listByTag(String resourceGroupName, String tagName, String tagValue) {
return new PagedIterable<>(this.listByTagAsync(resourceGroupName, tagName, tagValue));
}
@Override
public PagedFlux<GenericResource> listByTagAsync(String resourceGroupName, String tagName, String tagValue) {
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName,
ResourceManagerUtils.createOdataFilterForTags(tagName, tagValue), null, null),
res -> (GenericResourceInner) res));
}
@Override
public GenericResource.DefinitionStages.Blank define(String name) {
return new GenericResourceImpl(
name,
new GenericResourceInner(),
this.manager());
}
@Override
public boolean checkExistence(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().checkExistence(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
}
@Override
@Override
public boolean checkExistenceById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().checkExistenceById(id, apiVersion);
}
@Override
public GenericResource getById(String id) {
return this.getByIdAsync(id).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id) {
return this.getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.getByIdAsync(id, apiVersion));
}
@Override
public GenericResource getById(String id, String apiVersion) {
return this.getByIdAsync(id, apiVersion).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().getByIdAsync(id, apiVersion)
.map(this::wrapModel)
.map(r -> r.withApiVersion(apiVersion));
}
@Override
public Mono<Void> deleteByIdAsync(final String id) {
return getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.deleteByIdAsync(id, apiVersion));
}
@Override
public void deleteById(String id, String apiVersion) {
this.deleteByIdAsync(id, apiVersion).block();
}
@Override
public Mono<Void> deleteByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().deleteByIdAsync(id, apiVersion);
}
@Override
public GenericResource get(
String resourceGroupName,
String providerNamespace,
String resourceType,
String name) {
PagedIterable<GenericResource> genericResources = this.listByResourceGroup(resourceGroupName);
for (GenericResource resource : genericResources) {
if (resource.name().equalsIgnoreCase(name)
&& resource.resourceProviderNamespace().equalsIgnoreCase(providerNamespace)
&& resource.resourceType().equalsIgnoreCase(resourceType)) {
return resource;
}
}
return null;
}
@Override
public GenericResource get(
String resourceGroupName,
String resourceProviderNamespace,
String parentResourcePath,
String resourceType,
String resourceName,
String apiVersion) {
if (parentResourcePath == null) {
parentResourcePath = "";
}
GenericResourceInner inner = this.inner().get(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
GenericResourceImpl resource = new GenericResourceImpl(
resourceName,
inner,
this.manager());
return resource.withExistingResourceGroup(resourceGroupName)
.withProviderNamespace(resourceProviderNamespace)
.withParentResourcePath(parentResourcePath)
.withResourceType(resourceType)
.withApiVersion(apiVersion);
}
@Override
public void moveResources(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
this.moveResourcesAsync(sourceResourceGroupName, targetResourceGroup, resources).block();
}
@Override
public Mono<Void> moveResourcesAsync(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
ResourcesMoveInfo moveInfo = new ResourcesMoveInfo();
moveInfo.withTargetResourceGroup(targetResourceGroup.id());
moveInfo.withResources(resources);
return this.inner().moveResourcesAsync(sourceResourceGroupName, moveInfo);
}
public void delete(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion).block();
}
@Override
public Mono<Void> deleteAsync(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion);
}
@Override
protected GenericResourceImpl wrapModel(String id) {
return new GenericResourceImpl(id, new GenericResourceInner(), this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(id))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(id))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(id))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(id));
}
@Override
protected GenericResourceImpl wrapModel(GenericResourceInner inner) {
if (inner == null) {
return null;
}
return new GenericResourceImpl(inner.id(), inner, this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(inner.id()))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(inner.id()))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(inner.id()))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(inner.id()));
}
@Override
public Mono<GenericResourceInner> getInnerAsync(String groupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Get just by resource group and name is not supported. Please use other overloads."));
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Delete just by resource group and name is not supported. Please use other overloads."));
}
@Override
public Accepted<Void> beginDeleteById(String id) {
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.beginDeleteById(id, apiVersion);
}
@Override
public Accepted<Void> beginDeleteById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return AcceptedImpl.newAccepted(logger,
this.manager().serviceClient().getHttpPipeline(),
this.manager().serviceClient().getDefaultPollInterval(),
() -> this.inner().deleteByIdWithResponseAsync(id, apiVersion).block(),
Function.identity(),
Void.class,
null);
}
private Mono<String> getApiVersionFromIdAsync(final String id) {
return this.manager().providers().getByNameAsync(ResourceUtils.resourceProviderFromResourceId(id))
.map(provider -> ResourceUtils.defaultApiVersion(id, provider));
}
@Override
public PagedFlux<GenericResource> listAsync() {
return wrapPageAsync(PagedConverter.mapPage(this.inner().listAsync(),
res -> (GenericResourceInner) res));
}
@Override
public PagedFlux<GenericResource> listByResourceGroupAsync(String resourceGroupName) {
if (CoreUtils.isNullOrEmpty(resourceGroupName)) {
return new PagedFlux<>(() -> Mono.error(
new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")));
}
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName),
res -> (GenericResourceInner) res));
}
} | class GenericResourcesImpl
extends GroupableResourcesImpl<
GenericResource,
GenericResourceImpl,
GenericResourceInner,
ResourcesClient,
ResourceManager>
implements GenericResources {
private final ClientLogger logger = new ClientLogger(getClass());
public GenericResourcesImpl(ResourceManager resourceManager) {
super(resourceManager.serviceClient().getResources(), resourceManager);
}
@Override
public PagedIterable<GenericResource> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedIterable<GenericResource> listByResourceGroup(String groupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(groupName));
}
@Override
public PagedIterable<GenericResource> listByTag(String resourceGroupName, String tagName, String tagValue) {
return new PagedIterable<>(this.listByTagAsync(resourceGroupName, tagName, tagValue));
}
@Override
public PagedFlux<GenericResource> listByTagAsync(String resourceGroupName, String tagName, String tagValue) {
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName,
ResourceManagerUtils.createOdataFilterForTags(tagName, tagValue), null, null),
res -> (GenericResourceInner) res));
}
@Override
public GenericResource.DefinitionStages.Blank define(String name) {
return new GenericResourceImpl(
name,
new GenericResourceInner(),
this.manager());
}
@Override
public boolean checkExistence(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().checkExistence(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
}
@Override
@Override
public boolean checkExistenceById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().checkExistenceById(id, apiVersion);
}
@Override
public GenericResource getById(String id) {
return this.getByIdAsync(id).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
return this.getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.getByIdAsync(id, apiVersion));
}
@Override
public GenericResource getById(String id, String apiVersion) {
return this.getByIdAsync(id, apiVersion).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().getByIdAsync(id, apiVersion)
.map(this::wrapModel)
.map(r -> r.withApiVersion(apiVersion));
}
@Override
public Mono<Void> deleteByIdAsync(final String id) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
return getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.deleteByIdAsync(id, apiVersion));
}
@Override
public void deleteById(String id, String apiVersion) {
this.deleteByIdAsync(id, apiVersion).block();
}
@Override
public Mono<Void> deleteByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().deleteByIdAsync(id, apiVersion);
}
@Override
public GenericResource get(
String resourceGroupName,
String providerNamespace,
String resourceType,
String name) {
PagedIterable<GenericResource> genericResources = this.listByResourceGroup(resourceGroupName);
for (GenericResource resource : genericResources) {
if (resource.name().equalsIgnoreCase(name)
&& resource.resourceProviderNamespace().equalsIgnoreCase(providerNamespace)
&& resource.resourceType().equalsIgnoreCase(resourceType)) {
return resource;
}
}
return null;
}
@Override
public GenericResource get(
String resourceGroupName,
String resourceProviderNamespace,
String parentResourcePath,
String resourceType,
String resourceName,
String apiVersion) {
if (parentResourcePath == null) {
parentResourcePath = "";
}
GenericResourceInner inner = this.inner().get(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
GenericResourceImpl resource = new GenericResourceImpl(
resourceName,
inner,
this.manager());
return resource.withExistingResourceGroup(resourceGroupName)
.withProviderNamespace(resourceProviderNamespace)
.withParentResourcePath(parentResourcePath)
.withResourceType(resourceType)
.withApiVersion(apiVersion);
}
@Override
public void moveResources(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
this.moveResourcesAsync(sourceResourceGroupName, targetResourceGroup, resources).block();
}
@Override
public Mono<Void> moveResourcesAsync(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
ResourcesMoveInfo moveInfo = new ResourcesMoveInfo();
moveInfo.withTargetResourceGroup(targetResourceGroup.id());
moveInfo.withResources(resources);
return this.inner().moveResourcesAsync(sourceResourceGroupName, moveInfo);
}
public void delete(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion).block();
}
@Override
public Mono<Void> deleteAsync(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion);
}
@Override
protected GenericResourceImpl wrapModel(String id) {
return new GenericResourceImpl(id, new GenericResourceInner(), this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(id))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(id))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(id))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(id));
}
@Override
protected GenericResourceImpl wrapModel(GenericResourceInner inner) {
if (inner == null) {
return null;
}
return new GenericResourceImpl(inner.id(), inner, this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(inner.id()))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(inner.id()))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(inner.id()))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(inner.id()));
}
@Override
public Mono<GenericResourceInner> getInnerAsync(String groupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Get just by resource group and name is not supported. Please use other overloads."));
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Delete just by resource group and name is not supported. Please use other overloads."));
}
@Override
public Accepted<Void> beginDeleteById(String id) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.beginDeleteById(id, apiVersion);
}
@Override
public Accepted<Void> beginDeleteById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return AcceptedImpl.newAccepted(logger,
this.manager().serviceClient().getHttpPipeline(),
this.manager().serviceClient().getDefaultPollInterval(),
() -> this.inner().deleteByIdWithResponseAsync(id, apiVersion).block(),
Function.identity(),
Void.class,
null);
}
private Mono<String> getApiVersionFromIdAsync(final String id) {
return this.manager().providers().getByNameAsync(ResourceUtils.resourceProviderFromResourceId(id))
.map(provider -> ResourceUtils.defaultApiVersion(id, provider));
}
@Override
public PagedFlux<GenericResource> listAsync() {
return wrapPageAsync(PagedConverter.mapPage(this.inner().listAsync(),
res -> (GenericResourceInner) res));
}
@Override
public PagedFlux<GenericResource> listByResourceGroupAsync(String resourceGroupName) {
if (CoreUtils.isNullOrEmpty(resourceGroupName)) {
return new PagedFlux<>(() -> Mono.error(
new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")));
}
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName),
res -> (GenericResourceInner) res));
}
} |
Just think that if no async method, it cannot be used inside a flatmap for customer. Maybe they all could wait until required. | public boolean checkExistenceById(String id) {
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.checkExistenceById(id, apiVersion);
} | return this.checkExistenceById(id, apiVersion); | public boolean checkExistenceById(String id) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.checkExistenceById(id, apiVersion);
} | class GenericResourcesImpl
extends GroupableResourcesImpl<
GenericResource,
GenericResourceImpl,
GenericResourceInner,
ResourcesClient,
ResourceManager>
implements GenericResources {
private final ClientLogger logger = new ClientLogger(getClass());
public GenericResourcesImpl(ResourceManager resourceManager) {
super(resourceManager.serviceClient().getResources(), resourceManager);
}
@Override
public PagedIterable<GenericResource> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedIterable<GenericResource> listByResourceGroup(String groupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(groupName));
}
@Override
public PagedIterable<GenericResource> listByTag(String resourceGroupName, String tagName, String tagValue) {
return new PagedIterable<>(this.listByTagAsync(resourceGroupName, tagName, tagValue));
}
@Override
public PagedFlux<GenericResource> listByTagAsync(String resourceGroupName, String tagName, String tagValue) {
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName,
ResourceManagerUtils.createOdataFilterForTags(tagName, tagValue), null, null),
res -> (GenericResourceInner) res));
}
@Override
public GenericResource.DefinitionStages.Blank define(String name) {
return new GenericResourceImpl(
name,
new GenericResourceInner(),
this.manager());
}
@Override
public boolean checkExistence(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().checkExistence(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
}
@Override
@Override
public boolean checkExistenceById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().checkExistenceById(id, apiVersion);
}
@Override
public GenericResource getById(String id) {
return this.getByIdAsync(id).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id) {
return this.getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.getByIdAsync(id, apiVersion));
}
@Override
public GenericResource getById(String id, String apiVersion) {
return this.getByIdAsync(id, apiVersion).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().getByIdAsync(id, apiVersion)
.map(this::wrapModel)
.map(r -> r.withApiVersion(apiVersion));
}
@Override
public Mono<Void> deleteByIdAsync(final String id) {
return getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.deleteByIdAsync(id, apiVersion));
}
@Override
public void deleteById(String id, String apiVersion) {
this.deleteByIdAsync(id, apiVersion).block();
}
@Override
public Mono<Void> deleteByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().deleteByIdAsync(id, apiVersion);
}
@Override
public GenericResource get(
String resourceGroupName,
String providerNamespace,
String resourceType,
String name) {
PagedIterable<GenericResource> genericResources = this.listByResourceGroup(resourceGroupName);
for (GenericResource resource : genericResources) {
if (resource.name().equalsIgnoreCase(name)
&& resource.resourceProviderNamespace().equalsIgnoreCase(providerNamespace)
&& resource.resourceType().equalsIgnoreCase(resourceType)) {
return resource;
}
}
return null;
}
@Override
public GenericResource get(
String resourceGroupName,
String resourceProviderNamespace,
String parentResourcePath,
String resourceType,
String resourceName,
String apiVersion) {
if (parentResourcePath == null) {
parentResourcePath = "";
}
GenericResourceInner inner = this.inner().get(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
GenericResourceImpl resource = new GenericResourceImpl(
resourceName,
inner,
this.manager());
return resource.withExistingResourceGroup(resourceGroupName)
.withProviderNamespace(resourceProviderNamespace)
.withParentResourcePath(parentResourcePath)
.withResourceType(resourceType)
.withApiVersion(apiVersion);
}
@Override
public void moveResources(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
this.moveResourcesAsync(sourceResourceGroupName, targetResourceGroup, resources).block();
}
@Override
public Mono<Void> moveResourcesAsync(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
ResourcesMoveInfo moveInfo = new ResourcesMoveInfo();
moveInfo.withTargetResourceGroup(targetResourceGroup.id());
moveInfo.withResources(resources);
return this.inner().moveResourcesAsync(sourceResourceGroupName, moveInfo);
}
public void delete(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion).block();
}
@Override
public Mono<Void> deleteAsync(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion);
}
@Override
protected GenericResourceImpl wrapModel(String id) {
return new GenericResourceImpl(id, new GenericResourceInner(), this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(id))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(id))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(id))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(id));
}
@Override
protected GenericResourceImpl wrapModel(GenericResourceInner inner) {
if (inner == null) {
return null;
}
return new GenericResourceImpl(inner.id(), inner, this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(inner.id()))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(inner.id()))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(inner.id()))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(inner.id()));
}
@Override
public Mono<GenericResourceInner> getInnerAsync(String groupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Get just by resource group and name is not supported. Please use other overloads."));
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Delete just by resource group and name is not supported. Please use other overloads."));
}
@Override
public Accepted<Void> beginDeleteById(String id) {
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.beginDeleteById(id, apiVersion);
}
@Override
public Accepted<Void> beginDeleteById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return AcceptedImpl.newAccepted(logger,
this.manager().serviceClient().getHttpPipeline(),
this.manager().serviceClient().getDefaultPollInterval(),
() -> this.inner().deleteByIdWithResponseAsync(id, apiVersion).block(),
Function.identity(),
Void.class,
null);
}
private Mono<String> getApiVersionFromIdAsync(final String id) {
return this.manager().providers().getByNameAsync(ResourceUtils.resourceProviderFromResourceId(id))
.map(provider -> ResourceUtils.defaultApiVersion(id, provider));
}
@Override
public PagedFlux<GenericResource> listAsync() {
return wrapPageAsync(PagedConverter.mapPage(this.inner().listAsync(),
res -> (GenericResourceInner) res));
}
@Override
public PagedFlux<GenericResource> listByResourceGroupAsync(String resourceGroupName) {
if (CoreUtils.isNullOrEmpty(resourceGroupName)) {
return new PagedFlux<>(() -> Mono.error(
new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")));
}
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName),
res -> (GenericResourceInner) res));
}
} | class GenericResourcesImpl
extends GroupableResourcesImpl<
GenericResource,
GenericResourceImpl,
GenericResourceInner,
ResourcesClient,
ResourceManager>
implements GenericResources {
private final ClientLogger logger = new ClientLogger(getClass());
public GenericResourcesImpl(ResourceManager resourceManager) {
super(resourceManager.serviceClient().getResources(), resourceManager);
}
@Override
public PagedIterable<GenericResource> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedIterable<GenericResource> listByResourceGroup(String groupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(groupName));
}
@Override
public PagedIterable<GenericResource> listByTag(String resourceGroupName, String tagName, String tagValue) {
return new PagedIterable<>(this.listByTagAsync(resourceGroupName, tagName, tagValue));
}
@Override
public PagedFlux<GenericResource> listByTagAsync(String resourceGroupName, String tagName, String tagValue) {
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName,
ResourceManagerUtils.createOdataFilterForTags(tagName, tagValue), null, null),
res -> (GenericResourceInner) res));
}
@Override
public GenericResource.DefinitionStages.Blank define(String name) {
return new GenericResourceImpl(
name,
new GenericResourceInner(),
this.manager());
}
@Override
public boolean checkExistence(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().checkExistence(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
}
@Override
@Override
public boolean checkExistenceById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().checkExistenceById(id, apiVersion);
}
@Override
public GenericResource getById(String id) {
return this.getByIdAsync(id).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
return this.getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.getByIdAsync(id, apiVersion));
}
@Override
public GenericResource getById(String id, String apiVersion) {
return this.getByIdAsync(id, apiVersion).block();
}
@Override
public Mono<GenericResource> getByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().getByIdAsync(id, apiVersion)
.map(this::wrapModel)
.map(r -> r.withApiVersion(apiVersion));
}
@Override
public Mono<Void> deleteByIdAsync(final String id) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
return getApiVersionFromIdAsync(id)
.flatMap(apiVersion -> this.deleteByIdAsync(id, apiVersion));
}
@Override
public void deleteById(String id, String apiVersion) {
this.deleteByIdAsync(id, apiVersion).block();
}
@Override
public Mono<Void> deleteByIdAsync(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
return Mono.error(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return this.inner().deleteByIdAsync(id, apiVersion);
}
@Override
public GenericResource get(
String resourceGroupName,
String providerNamespace,
String resourceType,
String name) {
PagedIterable<GenericResource> genericResources = this.listByResourceGroup(resourceGroupName);
for (GenericResource resource : genericResources) {
if (resource.name().equalsIgnoreCase(name)
&& resource.resourceProviderNamespace().equalsIgnoreCase(providerNamespace)
&& resource.resourceType().equalsIgnoreCase(resourceType)) {
return resource;
}
}
return null;
}
@Override
public GenericResource get(
String resourceGroupName,
String resourceProviderNamespace,
String parentResourcePath,
String resourceType,
String resourceName,
String apiVersion) {
if (parentResourcePath == null) {
parentResourcePath = "";
}
GenericResourceInner inner = this.inner().get(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
apiVersion);
GenericResourceImpl resource = new GenericResourceImpl(
resourceName,
inner,
this.manager());
return resource.withExistingResourceGroup(resourceGroupName)
.withProviderNamespace(resourceProviderNamespace)
.withParentResourcePath(parentResourcePath)
.withResourceType(resourceType)
.withApiVersion(apiVersion);
}
@Override
public void moveResources(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
this.moveResourcesAsync(sourceResourceGroupName, targetResourceGroup, resources).block();
}
@Override
public Mono<Void> moveResourcesAsync(String sourceResourceGroupName,
ResourceGroup targetResourceGroup, List<String> resources) {
ResourcesMoveInfo moveInfo = new ResourcesMoveInfo();
moveInfo.withTargetResourceGroup(targetResourceGroup.id());
moveInfo.withResources(resources);
return this.inner().moveResourcesAsync(sourceResourceGroupName, moveInfo);
}
public void delete(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion).block();
}
@Override
public Mono<Void> deleteAsync(String resourceGroupName, String resourceProviderNamespace,
String parentResourcePath, String resourceType, String resourceName, String apiVersion) {
return this.inner().deleteAsync(resourceGroupName, resourceProviderNamespace,
parentResourcePath, resourceType, resourceName, apiVersion);
}
@Override
protected GenericResourceImpl wrapModel(String id) {
return new GenericResourceImpl(id, new GenericResourceInner(), this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(id))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(id))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(id))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(id));
}
@Override
protected GenericResourceImpl wrapModel(GenericResourceInner inner) {
if (inner == null) {
return null;
}
return new GenericResourceImpl(inner.id(), inner, this.manager())
.withExistingResourceGroup(ResourceUtils.groupFromResourceId(inner.id()))
.withProviderNamespace(ResourceUtils.resourceProviderFromResourceId(inner.id()))
.withResourceType(ResourceUtils.resourceTypeFromResourceId(inner.id()))
.withParentResourceId(ResourceUtils.parentResourceIdFromResourceId(inner.id()));
}
@Override
public Mono<GenericResourceInner> getInnerAsync(String groupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Get just by resource group and name is not supported. Please use other overloads."));
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Delete just by resource group and name is not supported. Please use other overloads."));
}
@Override
public Accepted<Void> beginDeleteById(String id) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
String apiVersion = getApiVersionFromIdAsync(id).block();
return this.beginDeleteById(id, apiVersion);
}
@Override
public Accepted<Void> beginDeleteById(String id, String apiVersion) {
if (CoreUtils.isNullOrEmpty(id)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'id' is required and cannot be null."));
}
if (CoreUtils.isNullOrEmpty(apiVersion)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Parameter 'apiVersion' is required and cannot be null."));
}
return AcceptedImpl.newAccepted(logger,
this.manager().serviceClient().getHttpPipeline(),
this.manager().serviceClient().getDefaultPollInterval(),
() -> this.inner().deleteByIdWithResponseAsync(id, apiVersion).block(),
Function.identity(),
Void.class,
null);
}
private Mono<String> getApiVersionFromIdAsync(final String id) {
return this.manager().providers().getByNameAsync(ResourceUtils.resourceProviderFromResourceId(id))
.map(provider -> ResourceUtils.defaultApiVersion(id, provider));
}
@Override
public PagedFlux<GenericResource> listAsync() {
return wrapPageAsync(PagedConverter.mapPage(this.inner().listAsync(),
res -> (GenericResourceInner) res));
}
@Override
public PagedFlux<GenericResource> listByResourceGroupAsync(String resourceGroupName) {
if (CoreUtils.isNullOrEmpty(resourceGroupName)) {
return new PagedFlux<>(() -> Mono.error(
new IllegalArgumentException("Parameter 'resourceGroupName' is required and cannot be null.")));
}
return wrapPageAsync(PagedConverter.mapPage(this.manager().serviceClient().getResources()
.listByResourceGroupAsync(resourceGroupName),
res -> (GenericResourceInner) res));
}
} |
This should be in `finally` block, so, even if the client failed to close, we should still attempt to dispose the scheduler. | public void close() {
try {
client.close();
scheduler.dispose();
} catch (Exception e) {
logger.info("partitionId[{}] Exception occurred disposing of consumer client.", partitionId);
}
} | scheduler.dispose(); | public void close() {
try {
client.close();
} catch (Exception error) {
logger.info("partitionId[{}] Exception occurred disposing of consumer client.", partitionId, error);
} finally {
scheduler.dispose();
}
} | class PartitionPump implements AutoCloseable {
private final String partitionId;
private final EventHubConsumerAsyncClient client;
private final Scheduler scheduler;
private final ClientLogger logger = new ClientLogger(PartitionPump.class);
/**
* Creates an instance with the given client and scheduler.
*
* @param partitionId Partition id for the pump.
* @param client Consumer associated with partition id.
* @param scheduler Scheduler for the consumer.
*/
PartitionPump(String partitionId, EventHubConsumerAsyncClient client, Scheduler scheduler) {
this.partitionId = partitionId;
this.client = client;
this.scheduler = scheduler;
}
EventHubConsumerAsyncClient getClient() {
return client;
}
/**
* Disposes of the scheduler and the consumer.
*/
@Override
} | class PartitionPump implements AutoCloseable {
private final String partitionId;
private final EventHubConsumerAsyncClient client;
private final Scheduler scheduler;
private final ClientLogger logger = new ClientLogger(PartitionPump.class);
/**
* Creates an instance with the given client and scheduler.
*
* @param partitionId Partition id for the pump.
* @param client Consumer associated with partition id.
* @param scheduler Scheduler for the consumer.
*/
PartitionPump(String partitionId, EventHubConsumerAsyncClient client, Scheduler scheduler) {
this.partitionId = partitionId;
this.client = client;
this.scheduler = scheduler;
}
EventHubConsumerAsyncClient getClient() {
return client;
}
/**
* Disposes of the scheduler and the consumer.
*/
@Override
} |
getHostname() should be after getConnectionId() to sync with the param order | public void onConnectionInit(Event event) {
logger.info("onConnectionInit connectionId[{}] hostname[{}] amqpHostname[{}]",
getHostname(), getConnectionId(), connectionOptions.getFullyQualifiedNamespace());
final Connection connection = event.getConnection();
connection.setHostname(connectionOptions.getFullyQualifiedNamespace());
connection.setContainer(getConnectionId());
final Map<Symbol, Object> properties = new HashMap<>();
connectionProperties.forEach((key, value) -> properties.put(Symbol.getSymbol(key), value));
connection.setProperties(properties);
connection.open();
} | getHostname(), getConnectionId(), connectionOptions.getFullyQualifiedNamespace()); | public void onConnectionInit(Event event) {
logger.info("onConnectionInit connectionId[{}] hostname[{}] amqpHostname[{}]",
getConnectionId(), getHostname(), connectionOptions.getFullyQualifiedNamespace());
final Connection connection = event.getConnection();
connection.setHostname(connectionOptions.getFullyQualifiedNamespace());
connection.setContainer(getConnectionId());
final Map<Symbol, Object> properties = new HashMap<>();
connectionProperties.forEach((key, value) -> properties.put(Symbol.getSymbol(key), value));
connection.setProperties(properties);
connection.open();
} | class ConnectionHandler extends Handler {
public static final int AMQPS_PORT = 5671;
static final Symbol PRODUCT = Symbol.valueOf("product");
static final Symbol VERSION = Symbol.valueOf("version");
static final Symbol PLATFORM = Symbol.valueOf("platform");
static final Symbol FRAMEWORK = Symbol.valueOf("framework");
static final Symbol USER_AGENT = Symbol.valueOf("user-agent");
static final int MAX_FRAME_SIZE = 65536;
private final Map<String, Object> connectionProperties;
private final ConnectionOptions connectionOptions;
private final SslPeerDetails peerDetails;
/**
* Creates a handler that handles proton-j's connection events.
*
* @param connectionId Identifier for this connection.
* @param connectionOptions Options used when creating the AMQP connection.
*/
public ConnectionHandler(final String connectionId, final ConnectionOptions connectionOptions,
SslPeerDetails peerDetails) {
super(connectionId,
Objects.requireNonNull(connectionOptions, "'connectionOptions' cannot be null.").getHostname(),
new ClientLogger(ConnectionHandler.class));
add(new Handshaker());
this.connectionOptions = connectionOptions;
this.connectionProperties = new HashMap<>();
this.connectionProperties.put(PRODUCT.toString(), connectionOptions.getProduct());
this.connectionProperties.put(VERSION.toString(), connectionOptions.getClientVersion());
this.connectionProperties.put(PLATFORM.toString(), ClientConstants.PLATFORM_INFO);
this.connectionProperties.put(FRAMEWORK.toString(), ClientConstants.FRAMEWORK_INFO);
final ClientOptions clientOptions = connectionOptions.getClientOptions();
final String applicationId = !CoreUtils.isNullOrEmpty(clientOptions.getApplicationId())
? clientOptions.getApplicationId()
: null;
final String userAgent = UserAgentUtil.toUserAgentString(applicationId, connectionOptions.getProduct(),
connectionOptions.getClientVersion(), null);
this.connectionProperties.put(USER_AGENT.toString(), userAgent);
this.peerDetails = Objects.requireNonNull(peerDetails, "'peerDetails' cannot be null.");
}
/**
* Gets properties to add when creating AMQP connection.
*
* @return A map of properties to add when creating AMQP connection.
*/
public Map<String, Object> getConnectionProperties() {
return connectionProperties;
}
/**
* Gets the port used when opening connection.
*
* @return The port used to open connection.
*/
public int getProtocolPort() {
return connectionOptions.getPort();
}
/**
* Gets the max frame size for this connection.
*
* @return The max frame size for this connection.
*/
public int getMaxFrameSize() {
return MAX_FRAME_SIZE;
}
/**
* Configures the SSL transport layer for the connection based on the {@link ConnectionOptions
*
* @param event The proton-j event.
* @param transport Transport to add layers to.
*/
protected void addTransportLayers(Event event, TransportInternal transport) {
final SslDomain sslDomain = Proton.sslDomain();
sslDomain.init(SslDomain.Mode.CLIENT);
final SslDomain.VerifyMode verifyMode = connectionOptions.getSslVerifyMode();
final SSLContext defaultSslContext;
if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
defaultSslContext = null;
} else {
try {
defaultSslContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new RuntimeException(
"Default SSL algorithm not found in JRE. Please check your JRE setup.", e));
}
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER_NAME) {
final StrictTlsContextSpi serviceProvider = new StrictTlsContextSpi(defaultSslContext);
final SSLContext context = new StrictTlsContext(serviceProvider, defaultSslContext.getProvider(),
defaultSslContext.getProtocol());
sslDomain.setSslContext(context);
transport.ssl(sslDomain, peerDetails);
return;
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER) {
sslDomain.setSslContext(defaultSslContext);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.VERIFY_PEER);
} else if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
logger.warning("connectionId[{}] '{}' is not secure.", getConnectionId(), verifyMode);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.ANONYMOUS_PEER);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"verifyMode is not supported: " + verifyMode));
}
transport.ssl(sslDomain);
}
@Override
@Override
public void onConnectionBound(Event event) {
final Transport transport = event.getTransport();
logger.info("onConnectionBound connectionId[{}] hostname[{}] peerDetails[{}:{}]", getConnectionId(),
getHostname(), peerDetails.getHostname(), peerDetails.getPort());
this.addTransportLayers(event, (TransportInternal) transport);
final Connection connection = event.getConnection();
if (connection != null) {
onNext(connection.getRemoteState());
}
}
@Override
public void onConnectionUnbound(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionUnbound hostname[{}], connectionId[{}], state[{}], remoteState[{}]",
connection.getHostname(), getConnectionId(), connection.getLocalState(), connection.getRemoteState());
if (connection.getRemoteState() != EndpointState.UNINITIALIZED) {
connection.free();
}
onNext(connection.getRemoteState());
}
@Override
public void onTransportError(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.warning("onTransportError hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
transport.unbind();
}
@Override
public void onTransportClosed(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.info("onTransportClosed hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
}
@Override
public void onConnectionLocalOpen(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalOpen", connection, error);
}
@Override
public void onConnectionRemoteOpen(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionRemoteOpen hostname[{}], connectionId[{}], remoteContainer[{}]",
connection.getHostname(), getConnectionId(), connection.getRemoteContainer());
onNext(connection.getRemoteState());
}
@Override
public void onConnectionLocalClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalClose", connection, error);
if (connection.getRemoteState() == EndpointState.CLOSED) {
final Transport transport = connection.getTransport();
if (transport != null) {
transport.unbind();
}
}
}
@Override
public void onConnectionRemoteClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getRemoteCondition();
logErrorCondition("onConnectionRemoteClose", connection, error);
if (error == null) {
onNext(connection.getRemoteState());
} else {
notifyErrorContext(connection, error);
}
}
@Override
public void onConnectionFinal(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionFinal", connection, error);
onNext(connection.getRemoteState());
close();
}
public AmqpErrorContext getErrorContext() {
return new AmqpErrorContext(getHostname());
}
private void notifyErrorContext(Connection connection, ErrorCondition condition) {
if (connection == null || connection.getRemoteState() == EndpointState.CLOSED) {
return;
}
if (condition == null) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"connectionId[%s]: notifyErrorContext does not have an ErrorCondition.", getConnectionId())));
}
final Throwable exception = ExceptionUtil.toException(condition.getCondition().toString(),
condition.getDescription(), getErrorContext());
onError(exception);
}
private void logErrorCondition(String eventName, Connection connection, ErrorCondition error) {
logger.info("{} connectionId[{}] hostname[{}] errorCondition[{}] errorDescription[{}]",
eventName,
getConnectionId(),
connection.getHostname(),
error != null ? error.getCondition() : ClientConstants.NOT_APPLICABLE,
error != null ? error.getDescription() : ClientConstants.NOT_APPLICABLE);
}
} | class ConnectionHandler extends Handler {
public static final int AMQPS_PORT = 5671;
static final Symbol PRODUCT = Symbol.valueOf("product");
static final Symbol VERSION = Symbol.valueOf("version");
static final Symbol PLATFORM = Symbol.valueOf("platform");
static final Symbol FRAMEWORK = Symbol.valueOf("framework");
static final Symbol USER_AGENT = Symbol.valueOf("user-agent");
static final int MAX_FRAME_SIZE = 65536;
private final Map<String, Object> connectionProperties;
private final ConnectionOptions connectionOptions;
private final SslPeerDetails peerDetails;
/**
* Creates a handler that handles proton-j's connection events.
*
* @param connectionId Identifier for this connection.
* @param connectionOptions Options used when creating the AMQP connection.
*/
public ConnectionHandler(final String connectionId, final ConnectionOptions connectionOptions,
SslPeerDetails peerDetails) {
super(connectionId,
Objects.requireNonNull(connectionOptions, "'connectionOptions' cannot be null.").getHostname(),
new ClientLogger(ConnectionHandler.class));
add(new Handshaker());
this.connectionOptions = connectionOptions;
this.connectionProperties = new HashMap<>();
this.connectionProperties.put(PRODUCT.toString(), connectionOptions.getProduct());
this.connectionProperties.put(VERSION.toString(), connectionOptions.getClientVersion());
this.connectionProperties.put(PLATFORM.toString(), ClientConstants.PLATFORM_INFO);
this.connectionProperties.put(FRAMEWORK.toString(), ClientConstants.FRAMEWORK_INFO);
final ClientOptions clientOptions = connectionOptions.getClientOptions();
final String applicationId = !CoreUtils.isNullOrEmpty(clientOptions.getApplicationId())
? clientOptions.getApplicationId()
: null;
final String userAgent = UserAgentUtil.toUserAgentString(applicationId, connectionOptions.getProduct(),
connectionOptions.getClientVersion(), null);
this.connectionProperties.put(USER_AGENT.toString(), userAgent);
this.peerDetails = Objects.requireNonNull(peerDetails, "'peerDetails' cannot be null.");
}
/**
* Gets properties to add when creating AMQP connection.
*
* @return A map of properties to add when creating AMQP connection.
*/
public Map<String, Object> getConnectionProperties() {
return connectionProperties;
}
/**
* Gets the port used when opening connection.
*
* @return The port used to open connection.
*/
public int getProtocolPort() {
return connectionOptions.getPort();
}
/**
* Gets the max frame size for this connection.
*
* @return The max frame size for this connection.
*/
public int getMaxFrameSize() {
return MAX_FRAME_SIZE;
}
/**
* Configures the SSL transport layer for the connection based on the {@link ConnectionOptions
*
* @param event The proton-j event.
* @param transport Transport to add layers to.
*/
protected void addTransportLayers(Event event, TransportInternal transport) {
final SslDomain sslDomain = Proton.sslDomain();
sslDomain.init(SslDomain.Mode.CLIENT);
final SslDomain.VerifyMode verifyMode = connectionOptions.getSslVerifyMode();
final SSLContext defaultSslContext;
if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
defaultSslContext = null;
} else {
try {
defaultSslContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new RuntimeException(
"Default SSL algorithm not found in JRE. Please check your JRE setup.", e));
}
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER_NAME) {
final StrictTlsContextSpi serviceProvider = new StrictTlsContextSpi(defaultSslContext);
final SSLContext context = new StrictTlsContext(serviceProvider, defaultSslContext.getProvider(),
defaultSslContext.getProtocol());
sslDomain.setSslContext(context);
transport.ssl(sslDomain, peerDetails);
return;
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER) {
sslDomain.setSslContext(defaultSslContext);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.VERIFY_PEER);
} else if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
logger.warning("connectionId[{}] '{}' is not secure.", getConnectionId(), verifyMode);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.ANONYMOUS_PEER);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"verifyMode is not supported: " + verifyMode));
}
transport.ssl(sslDomain);
}
@Override
@Override
public void onConnectionBound(Event event) {
final Transport transport = event.getTransport();
logger.info("onConnectionBound connectionId[{}] hostname[{}] peerDetails[{}:{}]", getConnectionId(),
getHostname(), peerDetails.getHostname(), peerDetails.getPort());
this.addTransportLayers(event, (TransportInternal) transport);
final Connection connection = event.getConnection();
if (connection != null) {
onNext(connection.getRemoteState());
}
}
@Override
public void onConnectionUnbound(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionUnbound hostname[{}], connectionId[{}], state[{}], remoteState[{}]",
connection.getHostname(), getConnectionId(), connection.getLocalState(), connection.getRemoteState());
if (connection.getRemoteState() != EndpointState.UNINITIALIZED) {
connection.free();
}
onNext(connection.getRemoteState());
}
@Override
public void onTransportError(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.warning("onTransportError hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
transport.unbind();
}
@Override
public void onTransportClosed(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.info("onTransportClosed hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
}
@Override
public void onConnectionLocalOpen(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalOpen", connection, error);
}
@Override
public void onConnectionRemoteOpen(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionRemoteOpen hostname[{}], connectionId[{}], remoteContainer[{}]",
connection.getHostname(), getConnectionId(), connection.getRemoteContainer());
onNext(connection.getRemoteState());
}
@Override
public void onConnectionLocalClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalClose", connection, error);
if (connection.getRemoteState() == EndpointState.CLOSED) {
final Transport transport = connection.getTransport();
if (transport != null) {
transport.unbind();
}
}
}
@Override
public void onConnectionRemoteClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getRemoteCondition();
logErrorCondition("onConnectionRemoteClose", connection, error);
if (error == null) {
onNext(connection.getRemoteState());
} else {
notifyErrorContext(connection, error);
}
}
@Override
public void onConnectionFinal(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionFinal", connection, error);
onNext(connection.getRemoteState());
close();
}
public AmqpErrorContext getErrorContext() {
return new AmqpErrorContext(getHostname());
}
private void notifyErrorContext(Connection connection, ErrorCondition condition) {
if (connection == null || connection.getRemoteState() == EndpointState.CLOSED) {
return;
}
if (condition == null) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"connectionId[%s]: notifyErrorContext does not have an ErrorCondition.", getConnectionId())));
}
final Throwable exception = ExceptionUtil.toException(condition.getCondition().toString(),
condition.getDescription(), getErrorContext());
onError(exception);
}
private void logErrorCondition(String eventName, Connection connection, ErrorCondition error) {
logger.info("{} connectionId[{}] hostname[{}] errorCondition[{}] errorDescription[{}]",
eventName,
getConnectionId(),
connection.getHostname(),
error != null ? error.getCondition() : ClientConstants.NOT_APPLICABLE,
error != null ? error.getDescription() : ClientConstants.NOT_APPLICABLE);
}
} |
Test/sample code. As `data` is of type [`object`](https://github.com/Azure/azure-rest-api-specs/blob/master/specification/resourcegraph/resource-manager/Microsoft.ResourceGraph/stable/2019-04-01/resourcegraph.json#L292-L295), it is not easy to use the result in Java. | public void testResourceGraph() {
QueryRequest queryRequest = new QueryRequest();
queryRequest.withSubscriptions(Arrays.asList(subscription));
queryRequest.withQuery("Resources | project name, type | order by name asc | limit 5");
QueryResponse queryResponse = resourceGraphManager.resourceProviders().resources(queryRequest);
Assert.assertTrue(queryResponse.count() > 0);
Assert.assertNotNull(queryResponse.data());
Assert.assertTrue(queryResponse.data() instanceof Map);
Map<String, Object> dataAsDict = (Map<String, Object>) queryResponse.data();
Assert.assertTrue(dataAsDict.containsKey("columns"));
Assert.assertTrue(dataAsDict.containsKey("rows"));
List<String> columns = (List<String>) dataAsDict.get("columns");
List<String> rows = (List<String>) dataAsDict.get("columns");
Assert.assertEquals(2, columns.size());
Assert.assertTrue(rows.size() > 0);
} | } | public void testResourceGraph() {
QueryRequest queryRequest = new QueryRequest();
queryRequest.withSubscriptions(Arrays.asList(subscription));
queryRequest.withQuery("Resources | project name, type | order by name asc | limit 5");
queryRequest.withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.TABLE));
QueryResponse queryResponse = resourceGraphManager.resourceProviders().resources(queryRequest);
Assert.assertTrue(queryResponse.count() > 0);
Assert.assertNotNull(queryResponse.data());
Assert.assertTrue(queryResponse.data() instanceof Map);
Map<String, Object> dataAsDict = (Map<String, Object>) queryResponse.data();
Assert.assertTrue(dataAsDict.containsKey("columns"));
Assert.assertTrue(dataAsDict.containsKey("rows"));
List<String> columns = (List<String>) dataAsDict.get("columns");
List<String> rows = (List<String>) dataAsDict.get("columns");
Assert.assertEquals(2, columns.size());
Assert.assertTrue(rows.size() > 0);
queryRequest.withOptions(new QueryRequestOptions().withResultFormat(ResultFormat.OBJECT_ARRAY));
queryResponse = resourceGraphManager.resourceProviders().resources(queryRequest);
Assert.assertTrue(queryResponse.count() > 0);
Assert.assertTrue(queryResponse.data() instanceof List);
List<Object> dataAsList = (List<Object>) queryResponse.data();
Map<String, String> itemAsDict = (Map<String, String>) dataAsList.iterator().next();
Assert.assertTrue(itemAsDict.containsKey("name"));
Assert.assertTrue(itemAsDict.containsKey("type"));
} | class ResourceGraphTests extends TestBase {
private ResourceGraphManager resourceGraphManager;
private String subscription;
@Override
protected void initializeClients(RestClient restClient, String defaultSubscription, String domain) throws IOException {
resourceGraphManager = ResourceGraphManager
.authenticate(restClient);
subscription = defaultSubscription;
}
@Override
protected void cleanUpResources() {
}
@Test
@Ignore
} | class ResourceGraphTests extends TestBase {
private ResourceGraphManager resourceGraphManager;
private String subscription;
@Override
protected void initializeClients(RestClient restClient, String defaultSubscription, String domain) throws IOException {
resourceGraphManager = ResourceGraphManager
.authenticate(restClient);
subscription = defaultSubscription;
}
@Override
protected void cleanUpResources() {
}
@Test
@Ignore
} |
"get() function of the token refresher should not return null." | private Mono<String> fetchFreshToken() {
Mono<String> tokenAsync = refresher.get();
if (tokenAsync == null) {
return FluxUtil.monoError(logger,
new RuntimeException("get() function for token refresher is null"));
}
return tokenAsync;
} | new RuntimeException("get() function for token refresher is null")); | private Mono<String> fetchFreshToken() {
Mono<String> tokenAsync = refresher.get();
if (tokenAsync == null) {
return FluxUtil.monoError(logger,
new RuntimeException("get() function of the token refresher should not return null."));
}
return tokenAsync;
} | class CommunicationTokenCredential implements AutoCloseable {
private static final int DEFAULT_EXPIRING_OFFSET_MINUTES = 10;
private final ClientLogger logger = new ClientLogger(CommunicationTokenCredential.class);
private AccessToken accessToken;
private final TokenParser tokenParser = new TokenParser();
private Supplier<Mono<String>> refresher;
private FetchingTask fetchingTask;
private boolean isClosed = false;
/**
* Create with serialized JWT token
*
* @param token serialized JWT token
*/
public CommunicationTokenCredential(String token) {
Objects.requireNonNull(token, "'token' cannot be null.");
setToken(token);
}
/**
* Create with tokenRefreshOptions, which includes a token supplier and optional serialized JWT token.
* If refresh proactively is true, callback function tokenRefresher will be called
* ahead of the token expiry by the number of minutes specified by
* CallbackOffsetMinutes defaulted to ten minutes. To modify this default, call
* setCallbackOffsetMinutes after construction
*
* @param tokenRefreshOptions implementation to supply fresh token when reqested
*/
public CommunicationTokenCredential(CommunicationTokenRefreshOptions tokenRefreshOptions) {
Supplier<Mono<String>> tokenRefresher = tokenRefreshOptions.getTokenRefresher();
Objects.requireNonNull(tokenRefresher, "'tokenRefresher' cannot be null.");
refresher = tokenRefresher;
if (tokenRefreshOptions.getToken() != null) {
setToken(tokenRefreshOptions.getToken());
if (tokenRefreshOptions.isRefreshProactively()) {
OffsetDateTime nextFetchTime = accessToken.getExpiresAt().minusMinutes(DEFAULT_EXPIRING_OFFSET_MINUTES);
fetchingTask = new FetchingTask(this, nextFetchTime);
}
}
}
/**
* Get Azure core access token from credential
*
* @return Asynchronous call to fetch actual token
*/
public Mono<AccessToken> getToken() {
if (isClosed) {
return FluxUtil.monoError(logger,
new RuntimeException("getToken called on closed CommunicationTokenCredential object"));
}
if ((accessToken == null || accessToken.isExpired()) && refresher != null) {
synchronized (this) {
if ((accessToken == null || accessToken.isExpired()) && refresher != null) {
return fetchFreshToken()
.map(token -> {
accessToken = tokenParser.parseJWTToken(token);
return accessToken;
});
}
}
}
return Mono.just(accessToken);
}
@Override
public void close() throws IOException {
isClosed = true;
if (fetchingTask != null) {
fetchingTask.stopTimer();
fetchingTask = null;
}
refresher = null;
}
boolean hasProactiveFetcher() {
return fetchingTask != null;
}
private void setToken(String freshToken) {
accessToken = tokenParser.parseJWTToken(freshToken);
if (fetchingTask != null) {
OffsetDateTime nextFetchTime = accessToken.getExpiresAt().minusMinutes(DEFAULT_EXPIRING_OFFSET_MINUTES);
fetchingTask.setNextFetchTime(nextFetchTime);
}
}
private static class FetchingTask {
private final CommunicationTokenCredential host;
private Timer expiringTimer;
private OffsetDateTime nextFetchTime;
FetchingTask(CommunicationTokenCredential tokenHost,
OffsetDateTime nextFetchAt) {
host = tokenHost;
nextFetchTime = nextFetchAt;
startTimer();
}
private synchronized void setNextFetchTime(OffsetDateTime newFetchTime) {
nextFetchTime = newFetchTime;
stopTimer();
startTimer();
}
private synchronized void startTimer() {
expiringTimer = new Timer();
Date expiring = Date.from(nextFetchTime.toInstant());
expiringTimer.schedule(new TokenExpiringTask(this), expiring);
}
private synchronized void stopTimer() {
if (expiringTimer == null) {
return;
}
expiringTimer.cancel();
expiringTimer.purge();
expiringTimer = null;
}
private Mono<String> fetchFreshToken() {
return host.fetchFreshToken();
}
private void setToken(String freshTokenString) {
host.setToken(freshTokenString);
}
private class TokenExpiringTask extends TimerTask {
private final ClientLogger logger = new ClientLogger(TokenExpiringTask.class);
private final FetchingTask tokenCache;
TokenExpiringTask(FetchingTask host) {
tokenCache = host;
}
@Override
public void run() {
try {
Mono<String> tokenAsync = tokenCache.fetchFreshToken();
tokenCache.setToken(tokenAsync.block());
} catch (Exception exception) {
logger.logExceptionAsError(new RuntimeException(exception));
}
}
}
}
} | class CommunicationTokenCredential implements AutoCloseable {
private static final int DEFAULT_EXPIRING_OFFSET_MINUTES = 10;
private final ClientLogger logger = new ClientLogger(CommunicationTokenCredential.class);
private AccessToken accessToken;
private final TokenParser tokenParser = new TokenParser();
private Supplier<Mono<String>> refresher;
private FetchingTask fetchingTask;
private boolean isClosed = false;
/**
* Create with serialized JWT token
*
* @param token serialized JWT token
*/
public CommunicationTokenCredential(String token) {
Objects.requireNonNull(token, "'token' cannot be null.");
setToken(token);
}
/**
* Create with tokenRefreshOptions, which includes a token supplier and optional serialized JWT token.
* If refresh proactively is true, callback function tokenRefresher will be called
* ahead of the token expiry by the number of minutes specified by
* CallbackOffsetMinutes defaulted to ten minutes. To modify this default, call
* setCallbackOffsetMinutes after construction
*
* @param tokenRefreshOptions implementation to supply fresh token when reqested
*/
public CommunicationTokenCredential(CommunicationTokenRefreshOptions tokenRefreshOptions) {
Supplier<Mono<String>> tokenRefresher = tokenRefreshOptions.getTokenRefresher();
Objects.requireNonNull(tokenRefresher, "'tokenRefresher' cannot be null.");
refresher = tokenRefresher;
if (tokenRefreshOptions.getInitialToken() != null) {
setToken(tokenRefreshOptions.getInitialToken());
if (tokenRefreshOptions.isRefreshProactively()) {
OffsetDateTime nextFetchTime = accessToken.getExpiresAt().minusMinutes(DEFAULT_EXPIRING_OFFSET_MINUTES);
fetchingTask = new FetchingTask(this, nextFetchTime);
}
}
}
/**
* Get Azure core access token from credential
*
* @return Asynchronous call to fetch actual token
*/
public Mono<AccessToken> getToken() {
if (isClosed) {
return FluxUtil.monoError(logger,
new RuntimeException("getToken called on closed CommunicationTokenCredential object"));
}
if ((accessToken == null || accessToken.isExpired()) && refresher != null) {
synchronized (this) {
if ((accessToken == null || accessToken.isExpired()) && refresher != null) {
return fetchFreshToken()
.map(token -> {
accessToken = tokenParser.parseJWTToken(token);
return accessToken;
});
}
}
}
return Mono.just(accessToken);
}
@Override
public void close() throws IOException {
isClosed = true;
if (fetchingTask != null) {
fetchingTask.stopTimer();
fetchingTask = null;
}
refresher = null;
}
boolean hasProactiveFetcher() {
return fetchingTask != null;
}
private void setToken(String freshToken) {
accessToken = tokenParser.parseJWTToken(freshToken);
if (fetchingTask != null) {
OffsetDateTime nextFetchTime = accessToken.getExpiresAt().minusMinutes(DEFAULT_EXPIRING_OFFSET_MINUTES);
fetchingTask.setNextFetchTime(nextFetchTime);
}
}
private static class FetchingTask {
private final CommunicationTokenCredential host;
private Timer expiringTimer;
private OffsetDateTime nextFetchTime;
FetchingTask(CommunicationTokenCredential tokenHost,
OffsetDateTime nextFetchAt) {
host = tokenHost;
nextFetchTime = nextFetchAt;
startTimer();
}
private synchronized void setNextFetchTime(OffsetDateTime newFetchTime) {
nextFetchTime = newFetchTime;
stopTimer();
startTimer();
}
private synchronized void startTimer() {
expiringTimer = new Timer();
Date expiring = Date.from(nextFetchTime.toInstant());
expiringTimer.schedule(new TokenExpiringTask(this), expiring);
}
private synchronized void stopTimer() {
if (expiringTimer == null) {
return;
}
expiringTimer.cancel();
expiringTimer.purge();
expiringTimer = null;
}
private Mono<String> fetchFreshToken() {
return host.fetchFreshToken();
}
private void setToken(String freshTokenString) {
host.setToken(freshTokenString);
}
private class TokenExpiringTask extends TimerTask {
private final ClientLogger logger = new ClientLogger(TokenExpiringTask.class);
private final FetchingTask tokenCache;
TokenExpiringTask(FetchingTask host) {
tokenCache = host;
}
@Override
public void run() {
try {
Mono<String> tokenAsync = tokenCache.fetchFreshToken();
tokenCache.setToken(tokenAsync.block());
} catch (Exception exception) {
logger.logExceptionAsError(new RuntimeException(exception));
}
}
}
}
} |
To be on the safer side, I would suggest using `compareToIgnoreCase` - as I am not sure if backend would always return range in upper case. Just a thought. | public FeedRangeEpkImpl(final Range<String> range) {
checkNotNull(range, "Argument 'range' must not be null");
if (range.getMin().compareTo(range.getMax()) > 0) {
throw new IllegalArgumentException("The provided range is incorrect min is larger than max");
}
this.range = range;
} | throw new IllegalArgumentException("The provided range is incorrect min is larger than max"); | public FeedRangeEpkImpl(final Range<String> range) {
checkNotNull(range, "Argument 'range' must not be null");
if (range.getMin().compareTo(range.getMax()) > 0) {
throw new IllegalArgumentException("The provided range is incorrect min is larger than max");
}
this.range = range;
} | class FeedRangeEpkImpl extends FeedRangeInternal {
private static final FeedRangeEpkImpl fullRangeEPK =
new FeedRangeEpkImpl(PartitionKeyInternalHelper.FullRange);
private final Range<String> range;
public Range<String> getRange() {
return this.range;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeedRangeEpkImpl that = (FeedRangeEpkImpl)o;
return Objects.equals(this.range, that.range);
}
@Override
public int hashCode() {
return Objects.hash(range);
}
public static FeedRangeEpkImpl forFullRange() {
return fullRangeEPK;
}
@Override
public Mono<Range<String>> getEffectiveRange(
IRoutingMapProvider routingMapProvider,
MetadataDiagnosticsContext metadataDiagnosticsCtx,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
return Mono.just(this.range);
}
@Override
public Mono<List<String>> getPartitionKeyRanges(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
final ArrayList<String> rangeList = new ArrayList<>();
if (pkRangeHolder.v != null) {
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
for (final PartitionKeyRange pkRange : pkRanges) {
rangeList.add(pkRange.getId());
}
}
return Mono.just(UnmodifiableList.unmodifiableList(rangeList));
});
});
}
@Override
public Mono<RxDocumentServiceRequest> populateFeedRangeFilteringHeaders(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
request.setEffectiveRange(this.range);
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
if (pkRangeHolder == null) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
if (pkRanges == null || pkRanges.size() == 0) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
if (pkRanges.size() > 1) {
GoneException goneException = new GoneException(
String.format("Epk Range '%s' is gone.", this.range));
BridgeInternal.setSubStatusCode(
goneException,
HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE);
return Mono.error(goneException);
}
final Range<String> singleRange = pkRanges.get(0).toRange();
if (singleRange.getMin().equals(this.range.getMin()) &&
singleRange.getMax().equals(this.range.getMax())) {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
} else {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
final Map<String, String> headers = request.getHeaders();
headers.put(
HttpConstants.HttpHeaders.READ_FEED_KEY_TYPE,
ReadFeedKeyType.EffectivePartitionKeyRange.name());
headers.put(
HttpConstants.HttpHeaders.START_EPK,
this.range.getMin());
headers.put(
HttpConstants.HttpHeaders.END_EPK,
this.range.getMax());
}
return Mono.just(request);
});
});
}
@Override
public void populatePropertyBag() {
super.populatePropertyBag();
setProperties(this, false);
}
@Override
public void setProperties(JsonSerializable serializable, boolean populateProperties) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
if (populateProperties) {
super.populatePropertyBag();
}
if (this.range != null) {
ModelBridgeInternal.populatePropertyBag(this.range);
setProperty(serializable, Constants.Properties.RANGE, this.range);
}
}
@Override
public void removeProperties(JsonSerializable serializable) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
serializable.remove(Constants.Properties.RANGE);
}
} | class FeedRangeEpkImpl extends FeedRangeInternal {
private static final FeedRangeEpkImpl fullRangeEPK =
new FeedRangeEpkImpl(PartitionKeyInternalHelper.FullRange);
private final Range<String> range;
public Range<String> getRange() {
return this.range;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeedRangeEpkImpl that = (FeedRangeEpkImpl)o;
return Objects.equals(this.range, that.range);
}
@Override
public int hashCode() {
return Objects.hash(range);
}
public static FeedRangeEpkImpl forFullRange() {
return fullRangeEPK;
}
@Override
public Mono<Range<String>> getEffectiveRange(
IRoutingMapProvider routingMapProvider,
MetadataDiagnosticsContext metadataDiagnosticsCtx,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
return Mono.just(this.range);
}
@Override
public Mono<List<String>> getPartitionKeyRanges(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
final ArrayList<String> rangeList = new ArrayList<>();
if (pkRangeHolder.v != null) {
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
for (final PartitionKeyRange pkRange : pkRanges) {
rangeList.add(pkRange.getId());
}
}
return Mono.just(UnmodifiableList.unmodifiableList(rangeList));
});
});
}
@Override
public Mono<RxDocumentServiceRequest> populateFeedRangeFilteringHeaders(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
request.setEffectiveRange(this.range);
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
if (pkRangeHolder == null) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
if (pkRanges == null || pkRanges.size() == 0) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
if (pkRanges.size() > 1) {
GoneException goneException = new GoneException(
String.format("Epk Range '%s' is gone.", this.range));
BridgeInternal.setSubStatusCode(
goneException,
HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE);
return Mono.error(goneException);
}
final Range<String> singleRange = pkRanges.get(0).toRange();
if (singleRange.getMin().equals(this.range.getMin()) &&
singleRange.getMax().equals(this.range.getMax())) {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
} else {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
final Map<String, String> headers = request.getHeaders();
headers.put(
HttpConstants.HttpHeaders.READ_FEED_KEY_TYPE,
ReadFeedKeyType.EffectivePartitionKeyRange.name());
headers.put(
HttpConstants.HttpHeaders.START_EPK,
this.range.getMin());
headers.put(
HttpConstants.HttpHeaders.END_EPK,
this.range.getMax());
}
return Mono.just(request);
});
});
}
@Override
public void populatePropertyBag() {
super.populatePropertyBag();
setProperties(this, false);
}
@Override
public void setProperties(JsonSerializable serializable, boolean populateProperties) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
if (populateProperties) {
super.populatePropertyBag();
}
if (this.range != null) {
ModelBridgeInternal.populatePropertyBag(this.range);
setProperty(serializable, Constants.Properties.RANGE, this.range);
}
}
@Override
public void removeProperties(JsonSerializable serializable) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
serializable.remove(Constants.Properties.RANGE);
}
} |
I checked the code again, at other places, we are using `compareTo()`, so I guess we will keep it the same here for consistency, doesn't make sense to introduce any weird behavior. | public FeedRangeEpkImpl(final Range<String> range) {
checkNotNull(range, "Argument 'range' must not be null");
if (range.getMin().compareTo(range.getMax()) > 0) {
throw new IllegalArgumentException("The provided range is incorrect min is larger than max");
}
this.range = range;
} | throw new IllegalArgumentException("The provided range is incorrect min is larger than max"); | public FeedRangeEpkImpl(final Range<String> range) {
checkNotNull(range, "Argument 'range' must not be null");
if (range.getMin().compareTo(range.getMax()) > 0) {
throw new IllegalArgumentException("The provided range is incorrect min is larger than max");
}
this.range = range;
} | class FeedRangeEpkImpl extends FeedRangeInternal {
private static final FeedRangeEpkImpl fullRangeEPK =
new FeedRangeEpkImpl(PartitionKeyInternalHelper.FullRange);
private final Range<String> range;
public Range<String> getRange() {
return this.range;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeedRangeEpkImpl that = (FeedRangeEpkImpl)o;
return Objects.equals(this.range, that.range);
}
@Override
public int hashCode() {
return Objects.hash(range);
}
public static FeedRangeEpkImpl forFullRange() {
return fullRangeEPK;
}
@Override
public Mono<Range<String>> getEffectiveRange(
IRoutingMapProvider routingMapProvider,
MetadataDiagnosticsContext metadataDiagnosticsCtx,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
return Mono.just(this.range);
}
@Override
public Mono<List<String>> getPartitionKeyRanges(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
final ArrayList<String> rangeList = new ArrayList<>();
if (pkRangeHolder.v != null) {
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
for (final PartitionKeyRange pkRange : pkRanges) {
rangeList.add(pkRange.getId());
}
}
return Mono.just(UnmodifiableList.unmodifiableList(rangeList));
});
});
}
@Override
public Mono<RxDocumentServiceRequest> populateFeedRangeFilteringHeaders(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
request.setEffectiveRange(this.range);
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
if (pkRangeHolder == null) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
if (pkRanges == null || pkRanges.size() == 0) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
if (pkRanges.size() > 1) {
GoneException goneException = new GoneException(
String.format("Epk Range '%s' is gone.", this.range));
BridgeInternal.setSubStatusCode(
goneException,
HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE);
return Mono.error(goneException);
}
final Range<String> singleRange = pkRanges.get(0).toRange();
if (singleRange.getMin().equals(this.range.getMin()) &&
singleRange.getMax().equals(this.range.getMax())) {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
} else {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
final Map<String, String> headers = request.getHeaders();
headers.put(
HttpConstants.HttpHeaders.READ_FEED_KEY_TYPE,
ReadFeedKeyType.EffectivePartitionKeyRange.name());
headers.put(
HttpConstants.HttpHeaders.START_EPK,
this.range.getMin());
headers.put(
HttpConstants.HttpHeaders.END_EPK,
this.range.getMax());
}
return Mono.just(request);
});
});
}
@Override
public void populatePropertyBag() {
super.populatePropertyBag();
setProperties(this, false);
}
@Override
public void setProperties(JsonSerializable serializable, boolean populateProperties) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
if (populateProperties) {
super.populatePropertyBag();
}
if (this.range != null) {
ModelBridgeInternal.populatePropertyBag(this.range);
setProperty(serializable, Constants.Properties.RANGE, this.range);
}
}
@Override
public void removeProperties(JsonSerializable serializable) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
serializable.remove(Constants.Properties.RANGE);
}
} | class FeedRangeEpkImpl extends FeedRangeInternal {
private static final FeedRangeEpkImpl fullRangeEPK =
new FeedRangeEpkImpl(PartitionKeyInternalHelper.FullRange);
private final Range<String> range;
public Range<String> getRange() {
return this.range;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeedRangeEpkImpl that = (FeedRangeEpkImpl)o;
return Objects.equals(this.range, that.range);
}
@Override
public int hashCode() {
return Objects.hash(range);
}
public static FeedRangeEpkImpl forFullRange() {
return fullRangeEPK;
}
@Override
public Mono<Range<String>> getEffectiveRange(
IRoutingMapProvider routingMapProvider,
MetadataDiagnosticsContext metadataDiagnosticsCtx,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
return Mono.just(this.range);
}
@Override
public Mono<List<String>> getPartitionKeyRanges(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
final ArrayList<String> rangeList = new ArrayList<>();
if (pkRangeHolder.v != null) {
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
for (final PartitionKeyRange pkRange : pkRanges) {
rangeList.add(pkRange.getId());
}
}
return Mono.just(UnmodifiableList.unmodifiableList(rangeList));
});
});
}
@Override
public Mono<RxDocumentServiceRequest> populateFeedRangeFilteringHeaders(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
request.setEffectiveRange(this.range);
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
if (pkRangeHolder == null) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
if (pkRanges == null || pkRanges.size() == 0) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
if (pkRanges.size() > 1) {
GoneException goneException = new GoneException(
String.format("Epk Range '%s' is gone.", this.range));
BridgeInternal.setSubStatusCode(
goneException,
HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE);
return Mono.error(goneException);
}
final Range<String> singleRange = pkRanges.get(0).toRange();
if (singleRange.getMin().equals(this.range.getMin()) &&
singleRange.getMax().equals(this.range.getMax())) {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
} else {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
final Map<String, String> headers = request.getHeaders();
headers.put(
HttpConstants.HttpHeaders.READ_FEED_KEY_TYPE,
ReadFeedKeyType.EffectivePartitionKeyRange.name());
headers.put(
HttpConstants.HttpHeaders.START_EPK,
this.range.getMin());
headers.put(
HttpConstants.HttpHeaders.END_EPK,
this.range.getMax());
}
return Mono.just(request);
});
});
}
@Override
public void populatePropertyBag() {
super.populatePropertyBag();
setProperties(this, false);
}
@Override
public void setProperties(JsonSerializable serializable, boolean populateProperties) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
if (populateProperties) {
super.populatePropertyBag();
}
if (this.range != null) {
ModelBridgeInternal.populatePropertyBag(this.range);
setProperty(serializable, Constants.Properties.RANGE, this.range);
}
}
@Override
public void removeProperties(JsonSerializable serializable) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
serializable.remove(Constants.Properties.RANGE);
}
} |
Yes - I actually checked that we will always use upper case intentionally to not have to use any ignore case comparisons. The "string" is always HEX for the range (at least in reality - why the class was made a Generic in the first place when it is only ever being used as Range<String> is a different question - it spans .Net and Java as well) | public FeedRangeEpkImpl(final Range<String> range) {
checkNotNull(range, "Argument 'range' must not be null");
if (range.getMin().compareTo(range.getMax()) > 0) {
throw new IllegalArgumentException("The provided range is incorrect min is larger than max");
}
this.range = range;
} | throw new IllegalArgumentException("The provided range is incorrect min is larger than max"); | public FeedRangeEpkImpl(final Range<String> range) {
checkNotNull(range, "Argument 'range' must not be null");
if (range.getMin().compareTo(range.getMax()) > 0) {
throw new IllegalArgumentException("The provided range is incorrect min is larger than max");
}
this.range = range;
} | class FeedRangeEpkImpl extends FeedRangeInternal {
private static final FeedRangeEpkImpl fullRangeEPK =
new FeedRangeEpkImpl(PartitionKeyInternalHelper.FullRange);
private final Range<String> range;
public Range<String> getRange() {
return this.range;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeedRangeEpkImpl that = (FeedRangeEpkImpl)o;
return Objects.equals(this.range, that.range);
}
@Override
public int hashCode() {
return Objects.hash(range);
}
public static FeedRangeEpkImpl forFullRange() {
return fullRangeEPK;
}
@Override
public Mono<Range<String>> getEffectiveRange(
IRoutingMapProvider routingMapProvider,
MetadataDiagnosticsContext metadataDiagnosticsCtx,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
return Mono.just(this.range);
}
@Override
public Mono<List<String>> getPartitionKeyRanges(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
final ArrayList<String> rangeList = new ArrayList<>();
if (pkRangeHolder.v != null) {
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
for (final PartitionKeyRange pkRange : pkRanges) {
rangeList.add(pkRange.getId());
}
}
return Mono.just(UnmodifiableList.unmodifiableList(rangeList));
});
});
}
@Override
public Mono<RxDocumentServiceRequest> populateFeedRangeFilteringHeaders(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
request.setEffectiveRange(this.range);
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
if (pkRangeHolder == null) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
if (pkRanges == null || pkRanges.size() == 0) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
if (pkRanges.size() > 1) {
GoneException goneException = new GoneException(
String.format("Epk Range '%s' is gone.", this.range));
BridgeInternal.setSubStatusCode(
goneException,
HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE);
return Mono.error(goneException);
}
final Range<String> singleRange = pkRanges.get(0).toRange();
if (singleRange.getMin().equals(this.range.getMin()) &&
singleRange.getMax().equals(this.range.getMax())) {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
} else {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
final Map<String, String> headers = request.getHeaders();
headers.put(
HttpConstants.HttpHeaders.READ_FEED_KEY_TYPE,
ReadFeedKeyType.EffectivePartitionKeyRange.name());
headers.put(
HttpConstants.HttpHeaders.START_EPK,
this.range.getMin());
headers.put(
HttpConstants.HttpHeaders.END_EPK,
this.range.getMax());
}
return Mono.just(request);
});
});
}
@Override
public void populatePropertyBag() {
super.populatePropertyBag();
setProperties(this, false);
}
@Override
public void setProperties(JsonSerializable serializable, boolean populateProperties) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
if (populateProperties) {
super.populatePropertyBag();
}
if (this.range != null) {
ModelBridgeInternal.populatePropertyBag(this.range);
setProperty(serializable, Constants.Properties.RANGE, this.range);
}
}
@Override
public void removeProperties(JsonSerializable serializable) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
serializable.remove(Constants.Properties.RANGE);
}
} | class FeedRangeEpkImpl extends FeedRangeInternal {
private static final FeedRangeEpkImpl fullRangeEPK =
new FeedRangeEpkImpl(PartitionKeyInternalHelper.FullRange);
private final Range<String> range;
public Range<String> getRange() {
return this.range;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeedRangeEpkImpl that = (FeedRangeEpkImpl)o;
return Objects.equals(this.range, that.range);
}
@Override
public int hashCode() {
return Objects.hash(range);
}
public static FeedRangeEpkImpl forFullRange() {
return fullRangeEPK;
}
@Override
public Mono<Range<String>> getEffectiveRange(
IRoutingMapProvider routingMapProvider,
MetadataDiagnosticsContext metadataDiagnosticsCtx,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
return Mono.just(this.range);
}
@Override
public Mono<List<String>> getPartitionKeyRanges(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
final ArrayList<String> rangeList = new ArrayList<>();
if (pkRangeHolder.v != null) {
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
for (final PartitionKeyRange pkRange : pkRanges) {
rangeList.add(pkRange.getId());
}
}
return Mono.just(UnmodifiableList.unmodifiableList(rangeList));
});
});
}
@Override
public Mono<RxDocumentServiceRequest> populateFeedRangeFilteringHeaders(
IRoutingMapProvider routingMapProvider,
RxDocumentServiceRequest request,
Mono<Utils.ValueHolder<DocumentCollection>> collectionResolutionMono) {
checkNotNull(
routingMapProvider,
"Argument 'routingMapProvider' must not be null");
checkNotNull(
request,
"Argument 'request' must not be null");
checkNotNull(
collectionResolutionMono,
"Argument 'collectionResolutionMono' must not be null");
MetadataDiagnosticsContext metadataDiagnosticsCtx =
BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics);
return collectionResolutionMono
.flatMap(documentCollectionResourceResponse -> {
final DocumentCollection collection = documentCollectionResourceResponse.v;
if (collection == null) {
throw new IllegalStateException("Collection cannot be null");
}
final String containerRid = collection.getResourceId();
request.setEffectiveRange(this.range);
return routingMapProvider
.tryGetOverlappingRangesAsync(
metadataDiagnosticsCtx,
containerRid,
this.range,
false,
null)
.flatMap(pkRangeHolder -> {
if (pkRangeHolder == null) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
final List<PartitionKeyRange> pkRanges = pkRangeHolder.v;
if (pkRanges == null || pkRanges.size() == 0) {
return Mono.error(new NotFoundException(
String.format("Stale cache for collection rid '%s'.",
containerRid)));
}
if (pkRanges.size() > 1) {
GoneException goneException = new GoneException(
String.format("Epk Range '%s' is gone.", this.range));
BridgeInternal.setSubStatusCode(
goneException,
HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE);
return Mono.error(goneException);
}
final Range<String> singleRange = pkRanges.get(0).toRange();
if (singleRange.getMin().equals(this.range.getMin()) &&
singleRange.getMax().equals(this.range.getMax())) {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
} else {
request.routeTo(new PartitionKeyRangeIdentity(pkRanges.get(0).getId()));
final Map<String, String> headers = request.getHeaders();
headers.put(
HttpConstants.HttpHeaders.READ_FEED_KEY_TYPE,
ReadFeedKeyType.EffectivePartitionKeyRange.name());
headers.put(
HttpConstants.HttpHeaders.START_EPK,
this.range.getMin());
headers.put(
HttpConstants.HttpHeaders.END_EPK,
this.range.getMax());
}
return Mono.just(request);
});
});
}
@Override
public void populatePropertyBag() {
super.populatePropertyBag();
setProperties(this, false);
}
@Override
public void setProperties(JsonSerializable serializable, boolean populateProperties) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
if (populateProperties) {
super.populatePropertyBag();
}
if (this.range != null) {
ModelBridgeInternal.populatePropertyBag(this.range);
setProperty(serializable, Constants.Properties.RANGE, this.range);
}
}
@Override
public void removeProperties(JsonSerializable serializable) {
checkNotNull(serializable, "Argument 'serializable' must not be null.");
serializable.remove(Constants.Properties.RANGE);
}
} |
why is it commented? | public void canBindHostnameAndSsl() throws Exception {
appServiceManager
.webApps()
.define(webappName)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.BASIC_B1)
.defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(webappName)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach()
.create();
WebApp webApp = appServiceManager.webApps().getByResourceGroup(rgName, webappName);
Assertions.assertNotNull(webApp);
if (!isPlaybackMode()) {
Response<String> response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
}
webApp.update().withManagedHostnameBindings(domain, webappName + "-1", webappName + "-2").apply();
if (!isPlaybackMode()) {
Response<String> response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
}
webApp
.update()
.defineSslBinding()
.forHostname(webappName + "." + domainName)
.withExistingAppServiceCertificateOrder(certificateOrder)
.withSniBasedSsl()
.attach()
.apply();
} | public void canBindHostnameAndSsl() throws Exception {
appServiceManager
.webApps()
.define(webappName)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.BASIC_B1)
.defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(webappName)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach()
.create();
WebApp webApp = appServiceManager.webApps().getByResourceGroup(rgName, webappName);
Assertions.assertNotNull(webApp);
if (!isPlaybackMode()) {
Response<String> response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
}
webApp.update().withManagedHostnameBindings(domain, webappName + "-1", webappName + "-2").apply();
if (!isPlaybackMode()) {
Response<String> response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
}
webApp
.update()
.defineSslBinding()
.forHostname(webappName + "." + domainName)
.withExistingAppServiceCertificateOrder(certificateOrder)
.withSniBasedSsl()
.attach()
.apply();
} | class HostnameSslTests extends AppServiceTest {
private String webappName = "";
private String appServicePlanName = "";
private String domainName = "";
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
super.initializeClients(httpPipeline, profile);
webappName = generateRandomResourceName("java-webapp-", 20);
appServicePlanName = generateRandomResourceName("java-asp-", 20);
domainName = super.domain.name();
}
@Test
@Disabled("Need a domain and a certificate")
} | class HostnameSslTests extends AppServiceTest {
private String webappName = "";
private String appServicePlanName = "";
private String domainName = "";
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
super.initializeClients(httpPipeline, profile);
webappName = generateRandomResourceName("java-webapp-", 20);
appServicePlanName = generateRandomResourceName("java-asp-", 20);
domainName = super.domain.name();
}
@Test
@Disabled("Need a domain and a certificate")
} | |
`SSLPeerUnverifiedException` is for okhttp. azure-core would be some different exception. I will update this test next time working on this feature. | public void canBindHostnameAndSsl() throws Exception {
appServiceManager
.webApps()
.define(webappName)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.BASIC_B1)
.defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(webappName)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach()
.create();
WebApp webApp = appServiceManager.webApps().getByResourceGroup(rgName, webappName);
Assertions.assertNotNull(webApp);
if (!isPlaybackMode()) {
Response<String> response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
}
webApp.update().withManagedHostnameBindings(domain, webappName + "-1", webappName + "-2").apply();
if (!isPlaybackMode()) {
Response<String> response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
}
webApp
.update()
.defineSslBinding()
.forHostname(webappName + "." + domainName)
.withExistingAppServiceCertificateOrder(certificateOrder)
.withSniBasedSsl()
.attach()
.apply();
} | public void canBindHostnameAndSsl() throws Exception {
appServiceManager
.webApps()
.define(webappName)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.BASIC_B1)
.defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(webappName)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach()
.create();
WebApp webApp = appServiceManager.webApps().getByResourceGroup(rgName, webappName);
Assertions.assertNotNull(webApp);
if (!isPlaybackMode()) {
Response<String> response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
}
webApp.update().withManagedHostnameBindings(domain, webappName + "-1", webappName + "-2").apply();
if (!isPlaybackMode()) {
Response<String> response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
response = curl("http:
Assertions.assertEquals(200, response.getStatusCode());
Assertions.assertNotNull(response.getValue());
}
webApp
.update()
.defineSslBinding()
.forHostname(webappName + "." + domainName)
.withExistingAppServiceCertificateOrder(certificateOrder)
.withSniBasedSsl()
.attach()
.apply();
} | class HostnameSslTests extends AppServiceTest {
private String webappName = "";
private String appServicePlanName = "";
private String domainName = "";
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
super.initializeClients(httpPipeline, profile);
webappName = generateRandomResourceName("java-webapp-", 20);
appServicePlanName = generateRandomResourceName("java-asp-", 20);
domainName = super.domain.name();
}
@Test
@Disabled("Need a domain and a certificate")
} | class HostnameSslTests extends AppServiceTest {
private String webappName = "";
private String appServicePlanName = "";
private String domainName = "";
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
super.initializeClients(httpPipeline, profile);
webappName = generateRandomResourceName("java-webapp-", 20);
appServicePlanName = generateRandomResourceName("java-asp-", 20);
domainName = super.domain.name();
}
@Test
@Disabled("Need a domain and a certificate")
} | |
I think we should, but not on info level, may be debug level logging. | private static void attemptToWarmupHttpClient(ReactorNettyClient reactorNettyClient) {
if (HTTP_CLIENT_WARMUP == null) {
return;
}
try {
((Mono<?>) HTTP_CLIENT_WARMUP.invoke(reactorNettyClient.httpClient)).block();
} catch (ClassCastException | WrongMethodTypeException throwable) {
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
} | private static void attemptToWarmupHttpClient(ReactorNettyClient reactorNettyClient) {
if (HTTP_CLIENT_WARMUP == null) {
return;
}
try {
((Mono<?>) HTTP_CLIENT_WARMUP.invoke(reactorNettyClient.httpClient)).block();
} catch (ClassCastException | WrongMethodTypeException throwable) {
logger.debug("Invoking HttpClient.warmup failed.", throwable);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
} | class ReactorNettyClient implements HttpClient {
private static final String REACTOR_NETTY_REQUEST_RECORD_KEY = "reactorNettyRequestRecordKey";
private static final Logger logger = LoggerFactory.getLogger(ReactorNettyClient.class.getSimpleName());
private static final MethodHandle HTTP_CLIENT_WARMUP;
static {
MethodHandle httpClientWarmup = null;
try {
httpClientWarmup = MethodHandles.publicLookup()
.findVirtual(reactor.netty.http.client.HttpClient.class, "warmup", MethodType.methodType(Mono.class));
} catch (Throwable throwable) {
}
HTTP_CLIENT_WARMUP = httpClientWarmup;
}
private HttpClientConfig httpClientConfig;
private reactor.netty.http.client.HttpClient httpClient;
private ConnectionProvider connectionProvider;
private ReactorNettyClient() {}
/**
* Creates ReactorNettyClient with un-pooled connection.
*/
public static ReactorNettyClient create(HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.newConnection()
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/**
* Creates ReactorNettyClient with {@link ConnectionProvider}.
*/
public static ReactorNettyClient createWithConnectionProvider(ConnectionProvider connectionProvider, HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.connectionProvider = connectionProvider;
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.create(connectionProvider)
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/*
* This enables fast warm up of HttpClient
*/
private void configureChannelPipelineHandlers() {
Configs configs = this.httpClientConfig.getConfigs();
if (this.httpClientConfig.getProxy() != null) {
this.httpClient = this.httpClient.proxy(typeSpec -> typeSpec.type(ProxyProvider.Proxy.HTTP)
.address(this.httpClientConfig.getProxy().getAddress()));
}
if (LoggerFactory.getLogger(REACTOR_NETWORK_LOG_CATEGORY).isTraceEnabled()) {
this.httpClient = this.httpClient.wiretap(REACTOR_NETWORK_LOG_CATEGORY, LogLevel.INFO);
}
this.httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(configs.getSslContext()))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) configs.getConnectionAcquireTimeout().toMillis())
.httpResponseDecoder(httpResponseDecoderSpec ->
httpResponseDecoderSpec.maxInitialLineLength(configs.getMaxHttpInitialLineLength())
.maxHeaderSize(configs.getMaxHttpHeaderSize())
.maxChunkSize(configs.getMaxHttpChunkSize())
.validateHeaders(true));
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
}
@Override
public Mono<HttpResponse> send(final HttpRequest request, Duration responseTimeout) {
Objects.requireNonNull(request.httpMethod());
Objects.requireNonNull(request.uri());
Objects.requireNonNull(this.httpClientConfig);
if(request.reactorNettyRequestRecord() == null) {
ReactorNettyRequestRecord reactorNettyRequestRecord = new ReactorNettyRequestRecord();
reactorNettyRequestRecord.setTimeCreated(Instant.now());
request.withReactorNettyRequestRecord(reactorNettyRequestRecord);
}
final AtomicReference<ReactorNettyHttpResponse> responseReference = new AtomicReference<>();
return this.httpClient
.keepAlive(this.httpClientConfig.isConnectionKeepAlive())
.port(request.port())
.responseTimeout(responseTimeout)
.request(HttpMethod.valueOf(request.httpMethod().toString()))
.uri(request.uri().toString())
.send(bodySendDelegate(request))
.responseConnection((reactorNettyResponse, reactorNettyConnection) -> {
HttpResponse httpResponse = new ReactorNettyHttpResponse(reactorNettyResponse,
reactorNettyConnection).withRequest(request);
responseReference.set((ReactorNettyHttpResponse) httpResponse);
return Mono.just(httpResponse);
})
.contextWrite(Context.of(REACTOR_NETTY_REQUEST_RECORD_KEY, request.reactorNettyRequestRecord()))
.doOnCancel(() -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.CANCELLED);
}
})
.onErrorMap(throwable -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.ERROR);
}
return throwable;
})
.single();
}
/**
* Delegate to send the request content.
*
* @param restRequest the Rest request contains the body to be sent
* @return a delegate upon invocation sets the request body in reactor-netty outbound object
*/
private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate(final HttpRequest restRequest) {
return (reactorNettyRequest, reactorNettyOutbound) -> {
for (HttpHeader header : restRequest.headers()) {
reactorNettyRequest.header(header.name(), header.value());
}
if (restRequest.body() != null) {
return reactorNettyOutbound.sendByteArray(restRequest.body());
} else {
return reactorNettyOutbound;
}
};
}
@Override
public void shutdown() {
if (this.connectionProvider != null) {
this.connectionProvider.dispose();
}
}
private static ConnectionObserver getConnectionObserver() {
return (conn, state) -> {
Instant time = Instant.now();
if (state.equals(HttpClientState.CONNECTED) || state.equals(HttpClientState.ACQUIRED)) {
if (conn instanceof ConnectionObserver) {
ConnectionObserver observer = (ConnectionObserver) conn;
ReactorNettyRequestRecord requestRecord =
observer.currentContext().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConnected(time);
}
} else if (state.equals(HttpClientState.CONFIGURED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConfigured(time);
}
} else if (state.equals(HttpClientState.REQUEST_SENT)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeSent(time);
}
} else if (state.equals(HttpClientState.RESPONSE_RECEIVED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeReceived(time);
}
}
};
}
private static class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation or error is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation or error happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseOnNotSubscribedResponse(ReactorNettyResponseState reactorNettyResponseState) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, reactorNettyResponseState)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
}
private enum ReactorNettyResponseState {
NOT_SUBSCRIBED,
SUBSCRIBED,
CANCELLED,
ERROR;
}
} | class ReactorNettyClient implements HttpClient {
private static final String REACTOR_NETTY_REQUEST_RECORD_KEY = "reactorNettyRequestRecordKey";
private static final Logger logger = LoggerFactory.getLogger(ReactorNettyClient.class.getSimpleName());
private static final MethodHandle HTTP_CLIENT_WARMUP;
static {
MethodHandle httpClientWarmup = null;
try {
httpClientWarmup = MethodHandles.publicLookup()
.findVirtual(reactor.netty.http.client.HttpClient.class, "warmup", MethodType.methodType(Mono.class));
} catch (IllegalAccessException | NoSuchMethodException ex) {
}
HTTP_CLIENT_WARMUP = httpClientWarmup;
}
private HttpClientConfig httpClientConfig;
private reactor.netty.http.client.HttpClient httpClient;
private ConnectionProvider connectionProvider;
private ReactorNettyClient() {}
/**
* Creates ReactorNettyClient with un-pooled connection.
*/
public static ReactorNettyClient create(HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.newConnection()
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/**
* Creates ReactorNettyClient with {@link ConnectionProvider}.
*/
public static ReactorNettyClient createWithConnectionProvider(ConnectionProvider connectionProvider, HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.connectionProvider = connectionProvider;
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.create(connectionProvider)
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/*
* This enables fast warm up of HttpClient
*/
private void configureChannelPipelineHandlers() {
Configs configs = this.httpClientConfig.getConfigs();
if (this.httpClientConfig.getProxy() != null) {
this.httpClient = this.httpClient.proxy(typeSpec -> typeSpec.type(ProxyProvider.Proxy.HTTP)
.address(this.httpClientConfig.getProxy().getAddress()));
}
if (LoggerFactory.getLogger(REACTOR_NETWORK_LOG_CATEGORY).isTraceEnabled()) {
this.httpClient = this.httpClient.wiretap(REACTOR_NETWORK_LOG_CATEGORY, LogLevel.INFO);
}
this.httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(configs.getSslContext()))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) configs.getConnectionAcquireTimeout().toMillis())
.httpResponseDecoder(httpResponseDecoderSpec ->
httpResponseDecoderSpec.maxInitialLineLength(configs.getMaxHttpInitialLineLength())
.maxHeaderSize(configs.getMaxHttpHeaderSize())
.maxChunkSize(configs.getMaxHttpChunkSize())
.validateHeaders(true));
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
}
@Override
public Mono<HttpResponse> send(final HttpRequest request, Duration responseTimeout) {
Objects.requireNonNull(request.httpMethod());
Objects.requireNonNull(request.uri());
Objects.requireNonNull(this.httpClientConfig);
if(request.reactorNettyRequestRecord() == null) {
ReactorNettyRequestRecord reactorNettyRequestRecord = new ReactorNettyRequestRecord();
reactorNettyRequestRecord.setTimeCreated(Instant.now());
request.withReactorNettyRequestRecord(reactorNettyRequestRecord);
}
final AtomicReference<ReactorNettyHttpResponse> responseReference = new AtomicReference<>();
return this.httpClient
.keepAlive(this.httpClientConfig.isConnectionKeepAlive())
.port(request.port())
.responseTimeout(responseTimeout)
.request(HttpMethod.valueOf(request.httpMethod().toString()))
.uri(request.uri().toString())
.send(bodySendDelegate(request))
.responseConnection((reactorNettyResponse, reactorNettyConnection) -> {
HttpResponse httpResponse = new ReactorNettyHttpResponse(reactorNettyResponse,
reactorNettyConnection).withRequest(request);
responseReference.set((ReactorNettyHttpResponse) httpResponse);
return Mono.just(httpResponse);
})
.contextWrite(Context.of(REACTOR_NETTY_REQUEST_RECORD_KEY, request.reactorNettyRequestRecord()))
.doOnCancel(() -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.CANCELLED);
}
})
.onErrorMap(throwable -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.ERROR);
}
return throwable;
})
.single();
}
/**
* Delegate to send the request content.
*
* @param restRequest the Rest request contains the body to be sent
* @return a delegate upon invocation sets the request body in reactor-netty outbound object
*/
private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate(final HttpRequest restRequest) {
return (reactorNettyRequest, reactorNettyOutbound) -> {
for (HttpHeader header : restRequest.headers()) {
reactorNettyRequest.header(header.name(), header.value());
}
if (restRequest.body() != null) {
return reactorNettyOutbound.sendByteArray(restRequest.body());
} else {
return reactorNettyOutbound;
}
};
}
@Override
public void shutdown() {
if (this.connectionProvider != null) {
this.connectionProvider.dispose();
}
}
private static ConnectionObserver getConnectionObserver() {
return (conn, state) -> {
Instant time = Instant.now();
if (state.equals(HttpClientState.CONNECTED) || state.equals(HttpClientState.ACQUIRED)) {
if (conn instanceof ConnectionObserver) {
ConnectionObserver observer = (ConnectionObserver) conn;
ReactorNettyRequestRecord requestRecord =
observer.currentContext().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConnected(time);
}
} else if (state.equals(HttpClientState.CONFIGURED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConfigured(time);
}
} else if (state.equals(HttpClientState.REQUEST_SENT)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeSent(time);
}
} else if (state.equals(HttpClientState.RESPONSE_RECEIVED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeReceived(time);
}
}
};
}
private static class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation or error is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation or error happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseOnNotSubscribedResponse(ReactorNettyResponseState reactorNettyResponseState) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, reactorNettyResponseState)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
}
private enum ReactorNettyResponseState {
NOT_SUBSCRIBED,
SUBSCRIBED,
CANCELLED,
ERROR;
}
} | |
We should null check this before calling `toMillis()`. | public AcsRecordingFileStatusUpdatedEventData setRecordingDuration(Duration recordingDuration) {
this.recordingDurationMs = recordingDuration.toMillis();
return this;
} | this.recordingDurationMs = recordingDuration.toMillis(); | public AcsRecordingFileStatusUpdatedEventData setRecordingDuration(Duration recordingDuration) {
if (recordingDuration != null) {
this.recordingDurationMs = recordingDuration.toMillis();
} else {
this.recordingDurationMs = null;
}
return this;
} | class AcsRecordingFileStatusUpdatedEventData {
/*
* The details of recording storage information
*/
@JsonProperty(value = "recordingStorageInfo")
private AcsRecordingStorageInfoProperties recordingStorageInfo;
/*
* The time at which the recording started
*/
@JsonProperty(value = "recordingStartTime")
private OffsetDateTime recordingStartTime;
/*
* The recording duration in milliseconds
*/
@JsonProperty(value = "recordingDurationMs")
private Long recordingDurationMs;
/*
* The reason for ending recording session
*/
@JsonProperty(value = "sessionEndReason")
private String sessionEndReason;
/**
* Get the recordingStorageInfo property: The details of recording storage information.
*
* @return the recordingStorageInfo value.
*/
public AcsRecordingStorageInfoProperties getRecordingStorageInfo() {
return this.recordingStorageInfo;
}
/**
* Set the recordingStorageInfo property: The details of recording storage information.
*
* @param recordingStorageInfo the recordingStorageInfo value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingStorageInfo(
AcsRecordingStorageInfoProperties recordingStorageInfo) {
this.recordingStorageInfo = recordingStorageInfo;
return this;
}
/**
* Get the recordingStartTime property: The time at which the recording started.
*
* @return the recordingStartTime value.
*/
public OffsetDateTime getRecordingStartTime() {
return this.recordingStartTime;
}
/**
* Set the recordingStartTime property: The time at which the recording started.
*
* @param recordingStartTime the recordingStartTime value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingStartTime(OffsetDateTime recordingStartTime) {
this.recordingStartTime = recordingStartTime;
return this;
}
/**
* Get the {@link Duration} of recordingDuration property: The recording duration.
*
* @return the recordingDuration value.
*/
public Duration getRecordingDuration() {
return Duration.ofMillis(this.recordingDurationMs);
}
/**
* Set the recordingDuration property: The recording duration.
*
* @param recordingDuration the recordingDuration value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
/**
* Get the sessionEndReason property: The reason for ending recording session.
*
* @return the sessionEndReason value.
*/
public String getSessionEndReason() {
return this.sessionEndReason;
}
/**
* Set the sessionEndReason property: The reason for ending recording session.
*
* @param sessionEndReason the sessionEndReason value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setSessionEndReason(String sessionEndReason) {
this.sessionEndReason = sessionEndReason;
return this;
}
} | class AcsRecordingFileStatusUpdatedEventData {
/*
* The details of recording storage information
*/
@JsonProperty(value = "recordingStorageInfo")
private AcsRecordingStorageInfoProperties recordingStorageInfo;
/*
* The time at which the recording started
*/
@JsonProperty(value = "recordingStartTime")
private OffsetDateTime recordingStartTime;
/*
* The recording duration in milliseconds
*/
@JsonProperty(value = "recordingDurationMs")
private Long recordingDurationMs;
/*
* The reason for ending recording session
*/
@JsonProperty(value = "sessionEndReason")
private String sessionEndReason;
/**
* Get the recordingStorageInfo property: The details of recording storage information.
*
* @return the recordingStorageInfo value.
*/
public AcsRecordingStorageInfoProperties getRecordingStorageInfo() {
return this.recordingStorageInfo;
}
/**
* Set the recordingStorageInfo property: The details of recording storage information.
*
* @param recordingStorageInfo the recordingStorageInfo value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingStorageInfo(
AcsRecordingStorageInfoProperties recordingStorageInfo) {
this.recordingStorageInfo = recordingStorageInfo;
return this;
}
/**
* Get the recordingStartTime property: The time at which the recording started.
*
* @return the recordingStartTime value.
*/
public OffsetDateTime getRecordingStartTime() {
return this.recordingStartTime;
}
/**
* Set the recordingStartTime property: The time at which the recording started.
*
* @param recordingStartTime the recordingStartTime value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingStartTime(OffsetDateTime recordingStartTime) {
this.recordingStartTime = recordingStartTime;
return this;
}
/**
* Get the {@link Duration} of recordingDuration property: The recording duration.
*
* @return the recordingDuration value.
*/
public Duration getRecordingDuration() {
if (this.recordingDurationMs != null) {
return Duration.ofMillis(this.recordingDurationMs);
}
return null;
}
/**
* Set the recordingDuration property: The recording duration.
*
* @param recordingDuration the recordingDuration value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
/**
* Get the sessionEndReason property: The reason for ending recording session.
*
* @return the sessionEndReason value.
*/
public String getSessionEndReason() {
return this.sessionEndReason;
}
/**
* Set the sessionEndReason property: The reason for ending recording session.
*
* @param sessionEndReason the sessionEndReason value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setSessionEndReason(String sessionEndReason) {
this.sessionEndReason = sessionEndReason;
return this;
}
} |
Wondering why the for-loop was removed here? | 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.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
} | assertHappyPath(result); | public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
}
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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());
}
} |
Do a null check. | public Duration getRecordingDuration() {
return Duration.ofMillis(this.recordingDurationMs);
} | return Duration.ofMillis(this.recordingDurationMs); | public Duration getRecordingDuration() {
if (this.recordingDurationMs != null) {
return Duration.ofMillis(this.recordingDurationMs);
}
return null;
} | class AcsRecordingFileStatusUpdatedEventData {
/*
* The details of recording storage information
*/
@JsonProperty(value = "recordingStorageInfo")
private AcsRecordingStorageInfoProperties recordingStorageInfo;
/*
* The time at which the recording started
*/
@JsonProperty(value = "recordingStartTime")
private OffsetDateTime recordingStartTime;
/*
* The recording duration in milliseconds
*/
@JsonProperty(value = "recordingDurationMs")
private Long recordingDurationMs;
/*
* The reason for ending recording session
*/
@JsonProperty(value = "sessionEndReason")
private String sessionEndReason;
/**
* Get the recordingStorageInfo property: The details of recording storage information.
*
* @return the recordingStorageInfo value.
*/
public AcsRecordingStorageInfoProperties getRecordingStorageInfo() {
return this.recordingStorageInfo;
}
/**
* Set the recordingStorageInfo property: The details of recording storage information.
*
* @param recordingStorageInfo the recordingStorageInfo value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingStorageInfo(
AcsRecordingStorageInfoProperties recordingStorageInfo) {
this.recordingStorageInfo = recordingStorageInfo;
return this;
}
/**
* Get the recordingStartTime property: The time at which the recording started.
*
* @return the recordingStartTime value.
*/
public OffsetDateTime getRecordingStartTime() {
return this.recordingStartTime;
}
/**
* Set the recordingStartTime property: The time at which the recording started.
*
* @param recordingStartTime the recordingStartTime value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingStartTime(OffsetDateTime recordingStartTime) {
this.recordingStartTime = recordingStartTime;
return this;
}
/**
* Get the {@link Duration} of recordingDuration property: The recording duration.
*
* @return the recordingDuration value.
*/
/**
* Set the recordingDuration property: The recording duration.
*
* @param recordingDuration the recordingDuration value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingDuration(Duration recordingDuration) {
this.recordingDurationMs = recordingDuration.toMillis();
return this;
}
/**
* Get the sessionEndReason property: The reason for ending recording session.
*
* @return the sessionEndReason value.
*/
public String getSessionEndReason() {
return this.sessionEndReason;
}
/**
* Set the sessionEndReason property: The reason for ending recording session.
*
* @param sessionEndReason the sessionEndReason value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setSessionEndReason(String sessionEndReason) {
this.sessionEndReason = sessionEndReason;
return this;
}
} | class AcsRecordingFileStatusUpdatedEventData {
/*
* The details of recording storage information
*/
@JsonProperty(value = "recordingStorageInfo")
private AcsRecordingStorageInfoProperties recordingStorageInfo;
/*
* The time at which the recording started
*/
@JsonProperty(value = "recordingStartTime")
private OffsetDateTime recordingStartTime;
/*
* The recording duration in milliseconds
*/
@JsonProperty(value = "recordingDurationMs")
private Long recordingDurationMs;
/*
* The reason for ending recording session
*/
@JsonProperty(value = "sessionEndReason")
private String sessionEndReason;
/**
* Get the recordingStorageInfo property: The details of recording storage information.
*
* @return the recordingStorageInfo value.
*/
public AcsRecordingStorageInfoProperties getRecordingStorageInfo() {
return this.recordingStorageInfo;
}
/**
* Set the recordingStorageInfo property: The details of recording storage information.
*
* @param recordingStorageInfo the recordingStorageInfo value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingStorageInfo(
AcsRecordingStorageInfoProperties recordingStorageInfo) {
this.recordingStorageInfo = recordingStorageInfo;
return this;
}
/**
* Get the recordingStartTime property: The time at which the recording started.
*
* @return the recordingStartTime value.
*/
public OffsetDateTime getRecordingStartTime() {
return this.recordingStartTime;
}
/**
* Set the recordingStartTime property: The time at which the recording started.
*
* @param recordingStartTime the recordingStartTime value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingStartTime(OffsetDateTime recordingStartTime) {
this.recordingStartTime = recordingStartTime;
return this;
}
/**
* Get the {@link Duration} of recordingDuration property: The recording duration.
*
* @return the recordingDuration value.
*/
/**
* Set the recordingDuration property: The recording duration.
*
* @param recordingDuration the recordingDuration value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setRecordingDuration(Duration recordingDuration) {
if (recordingDuration != null) {
this.recordingDurationMs = recordingDuration.toMillis();
} else {
this.recordingDurationMs = null;
}
return this;
}
/**
* Get the sessionEndReason property: The reason for ending recording session.
*
* @return the sessionEndReason value.
*/
public String getSessionEndReason() {
return this.sessionEndReason;
}
/**
* Set the sessionEndReason property: The reason for ending recording session.
*
* @param sessionEndReason the sessionEndReason value to set.
* @return the AcsRecordingFileStatusUpdatedEventData object itself.
*/
public AcsRecordingFileStatusUpdatedEventData setSessionEndReason(String sessionEndReason) {
this.sessionEndReason = sessionEndReason;
return this;
}
} |
The APIs result type now is PagedFlux<SmsSendResult> (not the Response<iterable<SmsSendResult>> which can be looped).. and I believe the introduction of .next() in the create step takes care of looping through the objects .. (I mostly followed the other tests in PhoneNumber for flux APIs :)) | 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.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
} | assertHappyPath(result); | public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
}
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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());
}
} |
Hmm I see, I think next only gets the next value in the page and does not loop through all the objects in the list | 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.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
} | assertHappyPath(result); | public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
}
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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 think you can do something like this so we can iterate through all the results @ankitarorabit : ``` PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(result); sendResults .iterableByPage().forEach(resp -> { assertHappyPath(result); }); ``` | 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.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
} | assertHappyPath(result); | public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
}
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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());
}
} |
Interesting, I thought I saw that the validation actually checked for 2 results but maybe I was mistaken, will use this code instead.. thanks! | 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.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
} | assertHappyPath(result); | public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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();
}
@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).next())
.assertNext(result -> {
assertHappyPath(result);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
PagedFlux<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
PagedIterable<SmsSendResult> sendResults = new PagedIterable<>(response);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
}
@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() == 404).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
PagedFlux<SmsSendResult> smsSendResults = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(smsSendResults)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResultList = smsSendResults.collectList().block();
for (SmsSendResult result : smsSendResultList) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
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());
}
} |
@srnagar is this an issue with codegen? | public ModelsRepositoryAPIImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-18";
}
if (host == null) {
this.host = ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT;
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
return new ModelsRepositoryAPIImpl(pipeline, serializerAdapter, host, apiVersion);
} | if (apiVersion == null) { | public ModelsRepositoryAPIImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-18";
}
if (host == null) {
this.host = ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT;
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
return new ModelsRepositoryAPIImpl(pipeline, serializerAdapter, host, apiVersion);
} | class ModelsRepositoryAPIImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
public ModelsRepositoryAPIImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* server parameter
*/
private String host;
/**
* Sets server parameter.
*
* @param host the host value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder host(String host) {
this.host = host;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of ModelsRepositoryAPIImpl with the provided parameters.
*
* @return an instance of ModelsRepositoryAPIImpl.
*/
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));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
} | class ModelsRepositoryAPIImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
public ModelsRepositoryAPIImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* server parameter
*/
private String host;
/**
* Sets server parameter.
*
* @param host the host value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder host(String host) {
this.host = host;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of ModelsRepositoryAPIImpl with the provided parameters.
*
* @return an instance of ModelsRepositoryAPIImpl.
*/
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));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
} |
@alzimmermsft are you referring to the formatting? | public ModelsRepositoryAPIImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-18";
}
if (host == null) {
this.host = ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT;
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
return new ModelsRepositoryAPIImpl(pipeline, serializerAdapter, host, apiVersion);
} | if (apiVersion == null) { | public ModelsRepositoryAPIImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-18";
}
if (host == null) {
this.host = ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT;
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
return new ModelsRepositoryAPIImpl(pipeline, serializerAdapter, host, apiVersion);
} | class ModelsRepositoryAPIImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
public ModelsRepositoryAPIImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* server parameter
*/
private String host;
/**
* Sets server parameter.
*
* @param host the host value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder host(String host) {
this.host = host;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of ModelsRepositoryAPIImpl with the provided parameters.
*
* @return an instance of ModelsRepositoryAPIImpl.
*/
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));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
} | class ModelsRepositoryAPIImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
public ModelsRepositoryAPIImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* server parameter
*/
private String host;
/**
* Sets server parameter.
*
* @param host the host value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder host(String host) {
this.host = host;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of ModelsRepositoryAPIImpl with the provided parameters.
*
* @return an instance of ModelsRepositoryAPIImpl.
*/
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));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
} |
Yeah, it was being flagged by Checkstyle linting | public ModelsRepositoryAPIImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-18";
}
if (host == null) {
this.host = ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT;
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
return new ModelsRepositoryAPIImpl(pipeline, serializerAdapter, host, apiVersion);
} | if (apiVersion == null) { | public ModelsRepositoryAPIImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-18";
}
if (host == null) {
this.host = ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT;
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
return new ModelsRepositoryAPIImpl(pipeline, serializerAdapter, host, apiVersion);
} | class ModelsRepositoryAPIImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
public ModelsRepositoryAPIImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* server parameter
*/
private String host;
/**
* Sets server parameter.
*
* @param host the host value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder host(String host) {
this.host = host;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of ModelsRepositoryAPIImpl with the provided parameters.
*
* @return an instance of ModelsRepositoryAPIImpl.
*/
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));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
} | class ModelsRepositoryAPIImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
public ModelsRepositoryAPIImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* server parameter
*/
private String host;
/**
* Sets server parameter.
*
* @param host the host value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder host(String host) {
this.host = host;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of ModelsRepositoryAPIImpl with the provided parameters.
*
* @return an instance of ModelsRepositoryAPIImpl.
*/
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));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
} |
yeah, I'll get this fixed in autorest. | public ModelsRepositoryAPIImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-18";
}
if (host == null) {
this.host = ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT;
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
return new ModelsRepositoryAPIImpl(pipeline, serializerAdapter, host, apiVersion);
} | if (apiVersion == null) { | public ModelsRepositoryAPIImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-18";
}
if (host == null) {
this.host = ModelsRepositoryConstants.DEFAULT_MODELS_REPOSITORY_ENDPOINT;
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
return new ModelsRepositoryAPIImpl(pipeline, serializerAdapter, host, apiVersion);
} | class ModelsRepositoryAPIImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
public ModelsRepositoryAPIImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* server parameter
*/
private String host;
/**
* Sets server parameter.
*
* @param host the host value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder host(String host) {
this.host = host;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of ModelsRepositoryAPIImpl with the provided parameters.
*
* @return an instance of ModelsRepositoryAPIImpl.
*/
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));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
} | class ModelsRepositoryAPIImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
public ModelsRepositoryAPIImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* server parameter
*/
private String host;
/**
* Sets server parameter.
*
* @param host the host value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder host(String host) {
this.host = host;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder 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 ModelsRepositoryAPIImplBuilder.
*/
public ModelsRepositoryAPIImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of ModelsRepositoryAPIImpl with the provided parameters.
*
* @return an instance of ModelsRepositoryAPIImpl.
*/
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));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
} |
@azabbasi these we disabled as they are failing in Linux and macOS, likely due to \ being in the URI | private static Stream<Arguments> getModelUriTestsSupplier() {
return Stream.of(
Arguments.of("https:
"https:
Arguments.of("https:
"https:
Arguments.of("file:
"file:
Arguments.of("file:
);
} | private static Stream<Arguments> getModelUriTestsSupplier() {
return Stream.of(
Arguments.of("https:
"https:
Arguments.of("https:
"https:
Arguments.of("file:
"file:
Arguments.of("file:
);
} | class DtmiConventionTests {
@ParameterizedTest
@CsvSource({
"dtmi:com:Example:Model;1, dtmi/com/example/model-1.json",
"dtmi:com:example:Model;1, dtmi/com/example/model-1.json",
"dtmi:com:example:Model:1, ",
"'',",
","
})
public void dtmiToPathTest(String input, String expected) {
if (expected == null) {
Assertions.assertThrows(IllegalArgumentException.class, () -> DtmiConventions.dtmiToPath(input));
return;
}
String actualValue = DtmiConventions.dtmiToPath(input);
Assertions.assertEquals(expected, actualValue);
}
@ParameterizedTest
@MethodSource("getModelUriTestsSupplier")
public void getModelUriTests(String repository, String expectedUri) throws URISyntaxException {
final String dtmi = "dtmi:com:example:Thermostat;1";
URI repositoryUri = DtmiConventions.convertToUri(repository);
if (expectedUri == null || expectedUri.isEmpty()) {
Assertions.assertThrows(IllegalArgumentException.class, () -> DtmiConventions.getModelUri(dtmi, repositoryUri, false));
return;
}
URI modelUri = DtmiConventions.getModelUri(dtmi, repositoryUri, false);
Assertions.assertEquals(expectedUri, modelUri.toString());
}
@ParameterizedTest
@CsvSource({
"dtmi:com:example:Thermostat;1, true",
"dtmi:contoso:scope:entity;2, true",
"dtmi:com:example:Thermostat:1, false",
"dtmi:com:example::Thermostat;1, false",
"com:example:Thermostat;1, false",
"'', false",
"null, false"
})
public void isValidDtmi(String dtmi, boolean expected) {
Assertions.assertEquals(expected, DtmiConventions.isValidDtmi(dtmi));
}
} | class DtmiConventionTests {
@ParameterizedTest
@CsvSource({
"dtmi:com:Example:Model;1, dtmi/com/example/model-1.json",
"dtmi:com:example:Model;1, dtmi/com/example/model-1.json",
"dtmi:com:example:Model:1, ",
"'',",
","
})
public void dtmiToPathTest(String input, String expected) {
if (expected == null) {
Assertions.assertThrows(IllegalArgumentException.class, () -> DtmiConventions.dtmiToPath(input));
return;
}
String actualValue = DtmiConventions.dtmiToPath(input);
Assertions.assertEquals(expected, actualValue);
}
@ParameterizedTest
@MethodSource("getModelUriTestsSupplier")
public void getModelUriTests(String repository, String expectedUri) throws URISyntaxException {
final String dtmi = "dtmi:com:example:Thermostat;1";
URI repositoryUri = DtmiConventions.convertToUri(repository);
if (expectedUri == null || expectedUri.isEmpty()) {
Assertions.assertThrows(IllegalArgumentException.class, () -> DtmiConventions.getModelUri(dtmi, repositoryUri, false));
return;
}
URI modelUri = DtmiConventions.getModelUri(dtmi, repositoryUri, false);
Assertions.assertEquals(expectedUri, modelUri.toString());
}
@ParameterizedTest
@CsvSource({
"dtmi:com:example:Thermostat;1, true",
"dtmi:contoso:scope:entity;2, true",
"dtmi:com:example:Thermostat:1, false",
"dtmi:com:example::Thermostat;1, false",
"com:example:Thermostat;1, false",
"'', false",
"null, false"
})
public void isValidDtmi(String dtmi, boolean expected) {
Assertions.assertEquals(expected, DtmiConventions.isValidDtmi(dtmi));
}
} | |
I am working on fixing these in the PR I have open you can merge this in if they are causing issues and cannot wait for the fix. | private static Stream<Arguments> getModelUriTestsSupplier() {
return Stream.of(
Arguments.of("https:
"https:
Arguments.of("https:
"https:
Arguments.of("file:
"file:
Arguments.of("file:
);
} | private static Stream<Arguments> getModelUriTestsSupplier() {
return Stream.of(
Arguments.of("https:
"https:
Arguments.of("https:
"https:
Arguments.of("file:
"file:
Arguments.of("file:
);
} | class DtmiConventionTests {
@ParameterizedTest
@CsvSource({
"dtmi:com:Example:Model;1, dtmi/com/example/model-1.json",
"dtmi:com:example:Model;1, dtmi/com/example/model-1.json",
"dtmi:com:example:Model:1, ",
"'',",
","
})
public void dtmiToPathTest(String input, String expected) {
if (expected == null) {
Assertions.assertThrows(IllegalArgumentException.class, () -> DtmiConventions.dtmiToPath(input));
return;
}
String actualValue = DtmiConventions.dtmiToPath(input);
Assertions.assertEquals(expected, actualValue);
}
@ParameterizedTest
@MethodSource("getModelUriTestsSupplier")
public void getModelUriTests(String repository, String expectedUri) throws URISyntaxException {
final String dtmi = "dtmi:com:example:Thermostat;1";
URI repositoryUri = DtmiConventions.convertToUri(repository);
if (expectedUri == null || expectedUri.isEmpty()) {
Assertions.assertThrows(IllegalArgumentException.class, () -> DtmiConventions.getModelUri(dtmi, repositoryUri, false));
return;
}
URI modelUri = DtmiConventions.getModelUri(dtmi, repositoryUri, false);
Assertions.assertEquals(expectedUri, modelUri.toString());
}
@ParameterizedTest
@CsvSource({
"dtmi:com:example:Thermostat;1, true",
"dtmi:contoso:scope:entity;2, true",
"dtmi:com:example:Thermostat:1, false",
"dtmi:com:example::Thermostat;1, false",
"com:example:Thermostat;1, false",
"'', false",
"null, false"
})
public void isValidDtmi(String dtmi, boolean expected) {
Assertions.assertEquals(expected, DtmiConventions.isValidDtmi(dtmi));
}
} | class DtmiConventionTests {
@ParameterizedTest
@CsvSource({
"dtmi:com:Example:Model;1, dtmi/com/example/model-1.json",
"dtmi:com:example:Model;1, dtmi/com/example/model-1.json",
"dtmi:com:example:Model:1, ",
"'',",
","
})
public void dtmiToPathTest(String input, String expected) {
if (expected == null) {
Assertions.assertThrows(IllegalArgumentException.class, () -> DtmiConventions.dtmiToPath(input));
return;
}
String actualValue = DtmiConventions.dtmiToPath(input);
Assertions.assertEquals(expected, actualValue);
}
@ParameterizedTest
@MethodSource("getModelUriTestsSupplier")
public void getModelUriTests(String repository, String expectedUri) throws URISyntaxException {
final String dtmi = "dtmi:com:example:Thermostat;1";
URI repositoryUri = DtmiConventions.convertToUri(repository);
if (expectedUri == null || expectedUri.isEmpty()) {
Assertions.assertThrows(IllegalArgumentException.class, () -> DtmiConventions.getModelUri(dtmi, repositoryUri, false));
return;
}
URI modelUri = DtmiConventions.getModelUri(dtmi, repositoryUri, false);
Assertions.assertEquals(expectedUri, modelUri.toString());
}
@ParameterizedTest
@CsvSource({
"dtmi:com:example:Thermostat;1, true",
"dtmi:contoso:scope:entity;2, true",
"dtmi:com:example:Thermostat:1, false",
"dtmi:com:example::Thermostat;1, false",
"com:example:Thermostat;1, false",
"'', false",
"null, false"
})
public void isValidDtmi(String dtmi, boolean expected) {
Assertions.assertEquals(expected, DtmiConventions.isValidDtmi(dtmi));
}
} | |
Correct. It'll validate when we call the inner overload of findBlobsByTags anyway, but since we will set the maxResults on the options here, I wanted to assert that it wasn't null just a step earlier. | PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
options.setMaxResultsPerPage(pageSize);
return withContext(context -> this.findBlobsByTags(options, marker, timeout, context));
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
} | StorageImplUtils.assertNotNull("options", options); | PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> withContext(context -> this.findBlobsByTags(
new FindBlobsOptions(options.getQuery()).setMaxResultsPerPage(pageSize), marker, timeout, context));
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
} | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
private final String accountName;
private final BlobServiceVersion serviceVersion;
private final CpkInfo customerProvidedKey;
private final EncryptionScope encryptionScope;
private final BlobContainerEncryptionScope blobContainerEncryptionScope;
private final boolean anonymousAccess;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param anonymousAccess Whether or not the client was built with anonymousAccess
*/
BlobServiceAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
CpkInfo customerProvidedKey, EncryptionScope encryptionScope,
BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) {
/* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer
when the sas token has already been applied. */
try {
URI.create(url);
} catch (IllegalArgumentException ex) {
throw logger.logExceptionAsError(ex);
}
this.azureBlobStorage = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.customerProvidedKey = customerProvidedKey;
this.encryptionScope = encryptionScope;
this.blobContainerEncryptionScope = blobContainerEncryptionScope;
this.anonymousAccess = anonymousAccess;
}
/**
* Initializes a {@link BlobContainerAsyncClient} object pointing to the specified container. This method does not
* create a container. It simply constructs the URL to the container and offers access to methods relevant to
* containers.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient
*
* @param containerName The name of the container to point to. A value of null or empty string will be interpreted
* as pointing to the root container and will be replaced by "$root".
* @return A {@link BlobContainerAsyncClient} object pointing to the specified container
*/
public BlobContainerAsyncClient getBlobContainerAsyncClient(String containerName) {
if (CoreUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
return new BlobContainerAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer
*
* @param containerName Name of the container to create
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> createBlobContainer(String containerName) {
try {
return createBlobContainerWithResponse(containerName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse
*
* @param containerName Name of the container to create
* @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this container is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
return withContext(context -> createBlobContainerWithResponse(containerName, metadata, accessType,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType, Context context) {
throwOnAnonymousAccess();
BlobContainerAsyncClient blobContainerAsyncClient = getBlobContainerAsyncClient(containerName);
return blobContainerAsyncClient.createWithResponse(metadata, accessType, context)
.map(response -> new SimpleResponse<>(response, blobContainerAsyncClient));
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlobContainer(String containerName) {
try {
return deleteBlobContainerWithResponse(containerName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName) {
try {
return withContext(context -> deleteBlobContainerWithResponse(containerName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName, Context context) {
throwOnAnonymousAccess();
return getBlobContainerAsyncClient(containerName).deleteWithResponse(null, context);
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureBlobStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers}
*
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers() {
try {
return this.listBlobContainers(new ListBlobContainersOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers
*
* @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options) {
try {
return listBlobContainersWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<BlobContainerItem> listBlobContainersWithOptionalTimeout(ListBlobContainersOptions options,
Duration timeout) {
throwOnAnonymousAccess();
BiFunction<String, Integer, Mono<PagedResponse<BlobContainerItem>>> func =
(marker, pageSize) -> {
ListBlobContainersOptions finalOptions = null;
if (pageSize != null) {
if (options == null) {
finalOptions = new ListBlobContainersOptions().setMaxResultsPerPage(pageSize);
} else {
finalOptions = options.setMaxResultsPerPage(pageSize);
}
}
return listBlobContainersSegment(marker, finalOptions, timeout);
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<BlobContainerItem>> listBlobContainersSegment(String marker,
ListBlobContainersOptions options, Duration timeout) {
options = options == null ? new ListBlobContainersOptions() : options;
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().listBlobContainersSegmentSinglePageAsync(
options.getPrefix(), marker, options.getMaxResultsPerPage(),
toIncludeTypes(options.getDetails()),
null, null, Context.NONE), timeout);
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag
*
* @param query Filters the results to return only blobs whose tags match the specified expression.
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(String query) {
return this.findBlobsByTags(new FindBlobsOptions(query));
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag
*
* @param options {@link FindBlobsOptions}
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options) {
try {
return findBlobsByTags(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
options.setMaxResultsPerPage(pageSize);
return this.findBlobsByTags(options, marker, timeout, context);
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<TaggedBlobItem>> findBlobsByTags(
FindBlobsOptions options, String marker,
Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().filterBlobsWithResponseAsync(null, null,
options.getQuery(), marker, options.getMaxResultsPerPage(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)), timeout)
.map(response -> {
List<TaggedBlobItem> value = response.getValue().getBlobs() == null
? Collections.emptyList()
: response.getValue().getBlobs().stream()
.map(ModelHelper::populateTaggedBlobItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getValue().getNextMarker(),
response.getDeserializedHeaders());
});
}
/**
* Converts {@link BlobContainerListDetails} into list of {@link ListBlobContainersIncludeType}
* that contains only options selected. If no option is selected then null is returned.
*
* @return a list of selected options converted into {@link ListBlobContainersIncludeType}, null if none
* of options has been selected.
*/
private List<ListBlobContainersIncludeType> toIncludeTypes(BlobContainerListDetails blobContainerListDetails) {
boolean hasDetails = blobContainerListDetails != null
&& (blobContainerListDetails.getRetrieveMetadata() || blobContainerListDetails.getRetrieveDeleted());
if (hasDetails) {
List<ListBlobContainersIncludeType> flags = new ArrayList<>(2);
if (blobContainerListDetails.getRetrieveDeleted()) {
flags.add(ListBlobContainersIncludeType.DELETED);
}
if (blobContainerListDetails.getRetrieveMetadata()) {
flags.add(ListBlobContainersIncludeType.METADATA);
}
return flags;
} else {
return null;
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getProperties}
*
* @return A reactive response containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceProperties> getProperties() {
try {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceProperties>> getPropertiesWithResponse() {
try {
return withContext(this::getPropertiesWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceProperties>> getPropertiesWithResponse(Context context) {
context = context == null ? Context.NONE : context;
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getPropertiesWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setProperties
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(BlobServiceProperties properties) {
try {
return setPropertiesWithResponse(properties).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties) {
try {
return withContext(context -> setPropertiesWithResponse(properties, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties, Context context) {
throwOnAnonymousAccess();
BlobServiceProperties finalProperties = null;
if (properties != null) {
finalProperties = new BlobServiceProperties();
finalProperties.setLogging(properties.getLogging());
if (finalProperties.getLogging() != null) {
StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion());
validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy");
}
finalProperties.setHourMetrics(properties.getHourMetrics());
if (finalProperties.getHourMetrics() != null) {
StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion());
validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention "
+ "Policy");
if (finalProperties.getHourMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("HourMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
finalProperties.setMinuteMetrics(properties.getMinuteMetrics());
if (finalProperties.getMinuteMetrics() != null) {
StorageImplUtils.assertNotNull("MinuteMetrics Version",
finalProperties.getMinuteMetrics().getVersion());
validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics "
+ "Retention Policy");
if (finalProperties.getMinuteMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
if (properties.getCors() != null) {
List<BlobCorsRule> corsRules = new ArrayList<>();
for (BlobCorsRule rule : properties.getCors()) {
corsRules.add(validatedCorsRule(rule));
}
finalProperties.setCors(corsRules);
}
finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion());
finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy());
validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days");
finalProperties.setStaticWebsite(properties.getStaticWebsite());
}
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().setPropertiesWithResponseAsync(finalProperties, null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Sets any null fields to "" since the service requires all Cors rules to be set if some are set.
* @param originalRule {@link BlobCorsRule}
* @return The validated {@link BlobCorsRule}
*/
private BlobCorsRule validatedCorsRule(BlobCorsRule originalRule) {
if (originalRule == null) {
return null;
}
BlobCorsRule validRule = new BlobCorsRule();
validRule.setAllowedHeaders(StorageImplUtils.emptyIfNull(originalRule.getAllowedHeaders()));
validRule.setAllowedMethods(StorageImplUtils.emptyIfNull(originalRule.getAllowedMethods()));
validRule.setAllowedOrigins(StorageImplUtils.emptyIfNull(originalRule.getAllowedOrigins()));
validRule.setExposedHeaders(StorageImplUtils.emptyIfNull(originalRule.getExposedHeaders()));
validRule.setMaxAgeInSeconds(originalRule.getMaxAgeInSeconds());
return validRule;
}
/**
* Validates a {@link BlobRetentionPolicy} according to service specs for set properties.
* @param retentionPolicy {@link BlobRetentionPolicy}
* @param policyName The name of the variable for errors.
*/
private void validateRetentionPolicy(BlobRetentionPolicy retentionPolicy, String policyName) {
if (retentionPolicy == null) {
return;
}
if (retentionPolicy.isEnabled()) {
StorageImplUtils.assertInBounds(policyName, retentionPolicy.getDays(), 1, 365);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry,
Context context) {
StorageImplUtils.assertNotNull("expiry", expiry);
if (start != null && !start.isBefore(expiry)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("`start` must be null or a datetime before `expiry`."));
}
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getUserDelegationKeyWithResponseAsync(
new KeyInfo()
.setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start))
.setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)),
null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatistics}
*
* @return A {@link Mono} containing the storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceStatistics> getStatistics() {
try {
return getStatisticsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse() {
try {
return withContext(this::getStatisticsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse(Context context) {
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getStatisticsWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo}
*
* @return A {@link Mono} containing containing the storage account info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getAccountInfoWithResponseAsync(context)
.map(rb -> {
ServicesGetAccountInfoHeaders hd = rb.getDeserializedHeaders();
return new SimpleResponse<>(rb, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind()));
});
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return generateAccountSas(accountSasSignatureValues, Context.NONE);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
throwOnAnonymousAccess();
return new AccountSasImplUtil(accountSasSignatureValues)
.generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context);
}
/**
* Checks if service client was built with credentials.
*/
private void throwOnAnonymousAccess() {
if (anonymousAccess) {
throw logger.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without "
+ "credentials"));
}
}
/**
* Restores a previously deleted container.
* If the container associated with provided <code>deletedContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer
*
* @param deletedContainerName The name of the previously deleted container.
* @param deletedContainerVersion The version of the previously deleted container.
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used
* to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> undeleteBlobContainer(
String deletedContainerName, String deletedContainerVersion) {
return this.undeleteBlobContainerWithResponse(new UndeleteBlobContainerOptions(deletedContainerName,
deletedContainerVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted container. The restored container
* will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>.
* Otherwise <code>deletedContainerName</code> is used as destination container name.
* If the container associated with provided <code>destinationContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse
*
* @param options {@link UndeleteBlobContainerOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options) {
try {
return withContext(context -> undeleteBlobContainerWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null;
String finalDestinationContainerName =
hasOptionalDestinationContainerName ? options.getDestinationContainerName()
: options.getDeletedContainerName();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getContainers().restoreWithResponseAsync(finalDestinationContainerName, null,
null, options.getDeletedContainerName(), options.getDeletedContainerVersion(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response,
getBlobContainerAsyncClient(finalDestinationContainerName)));
}
} | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
private final String accountName;
private final BlobServiceVersion serviceVersion;
private final CpkInfo customerProvidedKey;
private final EncryptionScope encryptionScope;
private final BlobContainerEncryptionScope blobContainerEncryptionScope;
private final boolean anonymousAccess;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param anonymousAccess Whether or not the client was built with anonymousAccess
*/
BlobServiceAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
CpkInfo customerProvidedKey, EncryptionScope encryptionScope,
BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) {
/* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer
when the sas token has already been applied. */
try {
URI.create(url);
} catch (IllegalArgumentException ex) {
throw logger.logExceptionAsError(ex);
}
this.azureBlobStorage = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.customerProvidedKey = customerProvidedKey;
this.encryptionScope = encryptionScope;
this.blobContainerEncryptionScope = blobContainerEncryptionScope;
this.anonymousAccess = anonymousAccess;
}
/**
* Initializes a {@link BlobContainerAsyncClient} object pointing to the specified container. This method does not
* create a container. It simply constructs the URL to the container and offers access to methods relevant to
* containers.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient
*
* @param containerName The name of the container to point to. A value of null or empty string will be interpreted
* as pointing to the root container and will be replaced by "$root".
* @return A {@link BlobContainerAsyncClient} object pointing to the specified container
*/
public BlobContainerAsyncClient getBlobContainerAsyncClient(String containerName) {
if (CoreUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
return new BlobContainerAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer
*
* @param containerName Name of the container to create
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> createBlobContainer(String containerName) {
try {
return createBlobContainerWithResponse(containerName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse
*
* @param containerName Name of the container to create
* @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this container is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
return withContext(context -> createBlobContainerWithResponse(containerName, metadata, accessType,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType, Context context) {
throwOnAnonymousAccess();
BlobContainerAsyncClient blobContainerAsyncClient = getBlobContainerAsyncClient(containerName);
return blobContainerAsyncClient.createWithResponse(metadata, accessType, context)
.map(response -> new SimpleResponse<>(response, blobContainerAsyncClient));
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlobContainer(String containerName) {
try {
return deleteBlobContainerWithResponse(containerName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName) {
try {
return withContext(context -> deleteBlobContainerWithResponse(containerName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName, Context context) {
throwOnAnonymousAccess();
return getBlobContainerAsyncClient(containerName).deleteWithResponse(null, context);
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureBlobStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers}
*
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers() {
try {
return this.listBlobContainers(new ListBlobContainersOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers
*
* @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options) {
try {
return listBlobContainersWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<BlobContainerItem> listBlobContainersWithOptionalTimeout(ListBlobContainersOptions options,
Duration timeout) {
throwOnAnonymousAccess();
BiFunction<String, Integer, Mono<PagedResponse<BlobContainerItem>>> func =
(marker, pageSize) -> {
ListBlobContainersOptions finalOptions;
if (pageSize != null) {
if (options == null) {
finalOptions = new ListBlobContainersOptions().setMaxResultsPerPage(pageSize);
} else {
finalOptions = new ListBlobContainersOptions()
.setMaxResultsPerPage(pageSize)
.setDetails(options.getDetails())
.setPrefix(options.getPrefix());
}
} else {
finalOptions = options;
}
return listBlobContainersSegment(marker, finalOptions, timeout);
};
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<BlobContainerItem>> listBlobContainersSegment(String marker,
ListBlobContainersOptions options, Duration timeout) {
options = options == null ? new ListBlobContainersOptions() : options;
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().listBlobContainersSegmentSinglePageAsync(
options.getPrefix(), marker, options.getMaxResultsPerPage(),
toIncludeTypes(options.getDetails()),
null, null, Context.NONE), timeout);
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag
*
* @param query Filters the results to return only blobs whose tags match the specified expression.
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(String query) {
return this.findBlobsByTags(new FindBlobsOptions(query));
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag
*
* @param options {@link FindBlobsOptions}
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options) {
try {
return findBlobsByTags(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
FindBlobsOptions finalOptions;
if (pageSize != null) {
finalOptions = new FindBlobsOptions(options.getQuery())
.setMaxResultsPerPage(pageSize);
} else {
finalOptions = options;
}
return this.findBlobsByTags(finalOptions, marker, timeout, context);
};
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<TaggedBlobItem>> findBlobsByTags(
FindBlobsOptions options, String marker,
Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().filterBlobsWithResponseAsync(null, null,
options.getQuery(), marker, options.getMaxResultsPerPage(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)), timeout)
.map(response -> {
List<TaggedBlobItem> value = response.getValue().getBlobs() == null
? Collections.emptyList()
: response.getValue().getBlobs().stream()
.map(ModelHelper::populateTaggedBlobItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getValue().getNextMarker(),
response.getDeserializedHeaders());
});
}
/**
* Converts {@link BlobContainerListDetails} into list of {@link ListBlobContainersIncludeType}
* that contains only options selected. If no option is selected then null is returned.
*
* @return a list of selected options converted into {@link ListBlobContainersIncludeType}, null if none
* of options has been selected.
*/
private List<ListBlobContainersIncludeType> toIncludeTypes(BlobContainerListDetails blobContainerListDetails) {
boolean hasDetails = blobContainerListDetails != null
&& (blobContainerListDetails.getRetrieveMetadata() || blobContainerListDetails.getRetrieveDeleted());
if (hasDetails) {
List<ListBlobContainersIncludeType> flags = new ArrayList<>(2);
if (blobContainerListDetails.getRetrieveDeleted()) {
flags.add(ListBlobContainersIncludeType.DELETED);
}
if (blobContainerListDetails.getRetrieveMetadata()) {
flags.add(ListBlobContainersIncludeType.METADATA);
}
return flags;
} else {
return null;
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getProperties}
*
* @return A reactive response containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceProperties> getProperties() {
try {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceProperties>> getPropertiesWithResponse() {
try {
return withContext(this::getPropertiesWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceProperties>> getPropertiesWithResponse(Context context) {
context = context == null ? Context.NONE : context;
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getPropertiesWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setProperties
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(BlobServiceProperties properties) {
try {
return setPropertiesWithResponse(properties).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties) {
try {
return withContext(context -> setPropertiesWithResponse(properties, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties, Context context) {
throwOnAnonymousAccess();
BlobServiceProperties finalProperties = null;
if (properties != null) {
finalProperties = new BlobServiceProperties();
finalProperties.setLogging(properties.getLogging());
if (finalProperties.getLogging() != null) {
StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion());
validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy");
}
finalProperties.setHourMetrics(properties.getHourMetrics());
if (finalProperties.getHourMetrics() != null) {
StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion());
validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention "
+ "Policy");
if (finalProperties.getHourMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("HourMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
finalProperties.setMinuteMetrics(properties.getMinuteMetrics());
if (finalProperties.getMinuteMetrics() != null) {
StorageImplUtils.assertNotNull("MinuteMetrics Version",
finalProperties.getMinuteMetrics().getVersion());
validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics "
+ "Retention Policy");
if (finalProperties.getMinuteMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
if (properties.getCors() != null) {
List<BlobCorsRule> corsRules = new ArrayList<>();
for (BlobCorsRule rule : properties.getCors()) {
corsRules.add(validatedCorsRule(rule));
}
finalProperties.setCors(corsRules);
}
finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion());
finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy());
validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days");
finalProperties.setStaticWebsite(properties.getStaticWebsite());
}
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().setPropertiesWithResponseAsync(finalProperties, null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Sets any null fields to "" since the service requires all Cors rules to be set if some are set.
* @param originalRule {@link BlobCorsRule}
* @return The validated {@link BlobCorsRule}
*/
private BlobCorsRule validatedCorsRule(BlobCorsRule originalRule) {
if (originalRule == null) {
return null;
}
BlobCorsRule validRule = new BlobCorsRule();
validRule.setAllowedHeaders(StorageImplUtils.emptyIfNull(originalRule.getAllowedHeaders()));
validRule.setAllowedMethods(StorageImplUtils.emptyIfNull(originalRule.getAllowedMethods()));
validRule.setAllowedOrigins(StorageImplUtils.emptyIfNull(originalRule.getAllowedOrigins()));
validRule.setExposedHeaders(StorageImplUtils.emptyIfNull(originalRule.getExposedHeaders()));
validRule.setMaxAgeInSeconds(originalRule.getMaxAgeInSeconds());
return validRule;
}
/**
* Validates a {@link BlobRetentionPolicy} according to service specs for set properties.
* @param retentionPolicy {@link BlobRetentionPolicy}
* @param policyName The name of the variable for errors.
*/
private void validateRetentionPolicy(BlobRetentionPolicy retentionPolicy, String policyName) {
if (retentionPolicy == null) {
return;
}
if (retentionPolicy.isEnabled()) {
StorageImplUtils.assertInBounds(policyName, retentionPolicy.getDays(), 1, 365);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry,
Context context) {
StorageImplUtils.assertNotNull("expiry", expiry);
if (start != null && !start.isBefore(expiry)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("`start` must be null or a datetime before `expiry`."));
}
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getUserDelegationKeyWithResponseAsync(
new KeyInfo()
.setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start))
.setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)),
null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatistics}
*
* @return A {@link Mono} containing the storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceStatistics> getStatistics() {
try {
return getStatisticsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse() {
try {
return withContext(this::getStatisticsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse(Context context) {
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getStatisticsWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo}
*
* @return A {@link Mono} containing containing the storage account info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getAccountInfoWithResponseAsync(context)
.map(rb -> {
ServicesGetAccountInfoHeaders hd = rb.getDeserializedHeaders();
return new SimpleResponse<>(rb, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind()));
});
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return generateAccountSas(accountSasSignatureValues, Context.NONE);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
throwOnAnonymousAccess();
return new AccountSasImplUtil(accountSasSignatureValues)
.generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context);
}
/**
* Checks if service client was built with credentials.
*/
private void throwOnAnonymousAccess() {
if (anonymousAccess) {
throw logger.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without "
+ "credentials"));
}
}
/**
* Restores a previously deleted container.
* If the container associated with provided <code>deletedContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer
*
* @param deletedContainerName The name of the previously deleted container.
* @param deletedContainerVersion The version of the previously deleted container.
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used
* to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> undeleteBlobContainer(
String deletedContainerName, String deletedContainerVersion) {
return this.undeleteBlobContainerWithResponse(new UndeleteBlobContainerOptions(deletedContainerName,
deletedContainerVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted container. The restored container
* will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>.
* Otherwise <code>deletedContainerName</code> is used as destination container name.
* If the container associated with provided <code>destinationContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse
*
* @param options {@link UndeleteBlobContainerOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options) {
try {
return withContext(context -> undeleteBlobContainerWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null;
String finalDestinationContainerName =
hasOptionalDestinationContainerName ? options.getDestinationContainerName()
: options.getDeletedContainerName();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getContainers().restoreWithResponseAsync(finalDestinationContainerName, null,
null, options.getDeletedContainerName(), options.getDeletedContainerVersion(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response,
getBlobContainerAsyncClient(finalDestinationContainerName)));
}
} |
if the underlying container partitionKeyPath is "/id" then this query will act as a single partition query and we will only be warming up the connections to a single parition. | public Mono<Void> openConnectionsAndInitCaches() {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id", UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
return cosmosPagedFlux.byPage().collectList().flatMap(feedResponse -> Mono.empty());
} | querySpec.setQueryText("select * from c where c.id = @id"); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
@mbhaskar thoughts ? | public Mono<Void> openConnectionsAndInitCaches() {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id", UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
return cosmosPagedFlux.byPage().collectList().flatMap(feedResponse -> Mono.empty());
} | querySpec.setQueryText("select * from c where c.id = @id"); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
Thats true. If "id" is partition key then `select * from c where c.id = @id` its prettymuch a single partition query | public Mono<Void> openConnectionsAndInitCaches() {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id", UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
return cosmosPagedFlux.byPage().collectList().flatMap(feedResponse -> Mono.empty());
} | querySpec.setQueryText("select * from c where c.id = @id"); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
I tested , it is not a single partition but yes also not covering all the partitions. Weird as it sound . Reverted to feed range query | public Mono<Void> openConnectionsAndInitCaches() {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id", UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
return cosmosPagedFlux.byPage().collectList().flatMap(feedResponse -> Mono.empty());
} | querySpec.setQueryText("select * from c where c.id = @id"); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
`fluxList` is defined outside of the for loop, and it is modified asynchronously inside the flatmap. Although because `feedRangesMono` emits only one single item technically there is no concurrency bug, but I think this can be improved. if `feedRangesMono` was Flux not a Mono you would have a race condition bug bellow when modifying `fluxList`. you generally don't need any of the list nor the AtomicReference. Please try to rewrite this method and only rely on using flatMap and merge that reduces the complexity a lot. | public Mono<Void> openConnectionsAndInitCaches() {
Mono<List<FeedRange>> feedRangesMono = this.getFeedRanges();
AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>();
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
return feedRangesMono.flatMap(feedRanges -> {
for (FeedRange feedRange : feedRanges) {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
sequentialList.set(Flux.merge(fluxList).collectList());
return sequentialList.get().flatMap(objects -> Mono.empty());
});
} | List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
you don't really need any of these lists or to worry about the thread-safety. This method can be rewritten using `flatMap` and `merge` without the use of any list or any synchronization construct i.e. `AtomicReference` | public Mono<Void> openConnectionsAndInitCaches() {
Mono<List<FeedRange>> feedRangesMono = this.getFeedRanges();
AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>();
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
return feedRangesMono.flatMap(feedRanges -> {
for (FeedRange feedRange : feedRanges) {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
sequentialList.set(Flux.merge(fluxList).collectList());
return sequentialList.get().flatMap(objects -> Mono.empty());
});
} | AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
Moved mono inside lambda , removed the AtomicReference (I would have preferred atomic if we have to use it outside lambda, and if we have flux of range instead of mono). However on fluxList all flux need to run in parallel for perf and I doesn't want chaining. Please let me know what is harm with this approach, also give your exact code, provide perf data base comparison between two approaches. Then i will think over it , otherwise I will keep it as it is | public Mono<Void> openConnectionsAndInitCaches() {
Mono<List<FeedRange>> feedRangesMono = this.getFeedRanges();
AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>();
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
return feedRangesMono.flatMap(feedRanges -> {
for (FeedRange feedRange : feedRanges) {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
sequentialList.set(Flux.merge(fluxList).collectList());
return sequentialList.get().flatMap(objects -> Mono.empty());
});
} | List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
Duplicate comment | public Mono<Void> openConnectionsAndInitCaches() {
Mono<List<FeedRange>> feedRangesMono = this.getFeedRanges();
AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>();
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
return feedRangesMono.flatMap(feedRanges -> {
for (FeedRange feedRange : feedRanges) {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
sequentialList.set(Flux.merge(fluxList).collectList());
return sequentialList.get().flatMap(objects -> Mono.empty());
});
} | AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
Should we log this (i.e. something we want to investigate when log appear) or fine with ignoring these exceptions? | private static void attemptToWarmupHttpClient(ReactorNettyClient reactorNettyClient) {
if (HTTP_CLIENT_WARMUP == null) {
return;
}
try {
((Mono<?>) HTTP_CLIENT_WARMUP.invoke(reactorNettyClient.httpClient)).block();
} catch (ClassCastException | WrongMethodTypeException throwable) {
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
} | private static void attemptToWarmupHttpClient(ReactorNettyClient reactorNettyClient) {
if (HTTP_CLIENT_WARMUP == null) {
return;
}
try {
((Mono<?>) HTTP_CLIENT_WARMUP.invoke(reactorNettyClient.httpClient)).block();
} catch (ClassCastException | WrongMethodTypeException throwable) {
logger.debug("Invoking HttpClient.warmup failed.", throwable);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
} | class ReactorNettyClient implements HttpClient {
private static final String REACTOR_NETTY_REQUEST_RECORD_KEY = "reactorNettyRequestRecordKey";
private static final Logger logger = LoggerFactory.getLogger(ReactorNettyClient.class.getSimpleName());
private static final MethodHandle HTTP_CLIENT_WARMUP;
static {
MethodHandle httpClientWarmup = null;
try {
httpClientWarmup = MethodHandles.publicLookup()
.findVirtual(reactor.netty.http.client.HttpClient.class, "warmup", MethodType.methodType(Mono.class));
} catch (Throwable throwable) {
}
HTTP_CLIENT_WARMUP = httpClientWarmup;
}
private HttpClientConfig httpClientConfig;
private reactor.netty.http.client.HttpClient httpClient;
private ConnectionProvider connectionProvider;
private ReactorNettyClient() {}
/**
* Creates ReactorNettyClient with un-pooled connection.
*/
public static ReactorNettyClient create(HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.newConnection()
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/**
* Creates ReactorNettyClient with {@link ConnectionProvider}.
*/
public static ReactorNettyClient createWithConnectionProvider(ConnectionProvider connectionProvider, HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.connectionProvider = connectionProvider;
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.create(connectionProvider)
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/*
* This enables fast warm up of HttpClient
*/
private void configureChannelPipelineHandlers() {
Configs configs = this.httpClientConfig.getConfigs();
if (this.httpClientConfig.getProxy() != null) {
this.httpClient = this.httpClient.proxy(typeSpec -> typeSpec.type(ProxyProvider.Proxy.HTTP)
.address(this.httpClientConfig.getProxy().getAddress()));
}
if (LoggerFactory.getLogger(REACTOR_NETWORK_LOG_CATEGORY).isTraceEnabled()) {
this.httpClient = this.httpClient.wiretap(REACTOR_NETWORK_LOG_CATEGORY, LogLevel.INFO);
}
this.httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(configs.getSslContext()))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) configs.getConnectionAcquireTimeout().toMillis())
.httpResponseDecoder(httpResponseDecoderSpec ->
httpResponseDecoderSpec.maxInitialLineLength(configs.getMaxHttpInitialLineLength())
.maxHeaderSize(configs.getMaxHttpHeaderSize())
.maxChunkSize(configs.getMaxHttpChunkSize())
.validateHeaders(true));
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
}
@Override
public Mono<HttpResponse> send(final HttpRequest request, Duration responseTimeout) {
Objects.requireNonNull(request.httpMethod());
Objects.requireNonNull(request.uri());
Objects.requireNonNull(this.httpClientConfig);
if(request.reactorNettyRequestRecord() == null) {
ReactorNettyRequestRecord reactorNettyRequestRecord = new ReactorNettyRequestRecord();
reactorNettyRequestRecord.setTimeCreated(Instant.now());
request.withReactorNettyRequestRecord(reactorNettyRequestRecord);
}
final AtomicReference<ReactorNettyHttpResponse> responseReference = new AtomicReference<>();
return this.httpClient
.keepAlive(this.httpClientConfig.isConnectionKeepAlive())
.port(request.port())
.responseTimeout(responseTimeout)
.request(HttpMethod.valueOf(request.httpMethod().toString()))
.uri(request.uri().toString())
.send(bodySendDelegate(request))
.responseConnection((reactorNettyResponse, reactorNettyConnection) -> {
HttpResponse httpResponse = new ReactorNettyHttpResponse(reactorNettyResponse,
reactorNettyConnection).withRequest(request);
responseReference.set((ReactorNettyHttpResponse) httpResponse);
return Mono.just(httpResponse);
})
.contextWrite(Context.of(REACTOR_NETTY_REQUEST_RECORD_KEY, request.reactorNettyRequestRecord()))
.doOnCancel(() -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.CANCELLED);
}
})
.onErrorMap(throwable -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.ERROR);
}
return throwable;
})
.single();
}
/**
* Delegate to send the request content.
*
* @param restRequest the Rest request contains the body to be sent
* @return a delegate upon invocation sets the request body in reactor-netty outbound object
*/
private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate(final HttpRequest restRequest) {
return (reactorNettyRequest, reactorNettyOutbound) -> {
for (HttpHeader header : restRequest.headers()) {
reactorNettyRequest.header(header.name(), header.value());
}
if (restRequest.body() != null) {
return reactorNettyOutbound.sendByteArray(restRequest.body());
} else {
return reactorNettyOutbound;
}
};
}
@Override
public void shutdown() {
if (this.connectionProvider != null) {
this.connectionProvider.dispose();
}
}
private static ConnectionObserver getConnectionObserver() {
return (conn, state) -> {
Instant time = Instant.now();
if (state.equals(HttpClientState.CONNECTED) || state.equals(HttpClientState.ACQUIRED)) {
if (conn instanceof ConnectionObserver) {
ConnectionObserver observer = (ConnectionObserver) conn;
ReactorNettyRequestRecord requestRecord =
observer.currentContext().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConnected(time);
}
} else if (state.equals(HttpClientState.CONFIGURED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConfigured(time);
}
} else if (state.equals(HttpClientState.REQUEST_SENT)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeSent(time);
}
} else if (state.equals(HttpClientState.RESPONSE_RECEIVED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeReceived(time);
}
}
};
}
private static class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation or error is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation or error happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseOnNotSubscribedResponse(ReactorNettyResponseState reactorNettyResponseState) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, reactorNettyResponseState)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
}
private enum ReactorNettyResponseState {
NOT_SUBSCRIBED,
SUBSCRIBED,
CANCELLED,
ERROR;
}
} | class ReactorNettyClient implements HttpClient {
private static final String REACTOR_NETTY_REQUEST_RECORD_KEY = "reactorNettyRequestRecordKey";
private static final Logger logger = LoggerFactory.getLogger(ReactorNettyClient.class.getSimpleName());
private static final MethodHandle HTTP_CLIENT_WARMUP;
static {
MethodHandle httpClientWarmup = null;
try {
httpClientWarmup = MethodHandles.publicLookup()
.findVirtual(reactor.netty.http.client.HttpClient.class, "warmup", MethodType.methodType(Mono.class));
} catch (IllegalAccessException | NoSuchMethodException ex) {
}
HTTP_CLIENT_WARMUP = httpClientWarmup;
}
private HttpClientConfig httpClientConfig;
private reactor.netty.http.client.HttpClient httpClient;
private ConnectionProvider connectionProvider;
private ReactorNettyClient() {}
/**
* Creates ReactorNettyClient with un-pooled connection.
*/
public static ReactorNettyClient create(HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.newConnection()
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/**
* Creates ReactorNettyClient with {@link ConnectionProvider}.
*/
public static ReactorNettyClient createWithConnectionProvider(ConnectionProvider connectionProvider, HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.connectionProvider = connectionProvider;
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.create(connectionProvider)
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/*
* This enables fast warm up of HttpClient
*/
private void configureChannelPipelineHandlers() {
Configs configs = this.httpClientConfig.getConfigs();
if (this.httpClientConfig.getProxy() != null) {
this.httpClient = this.httpClient.proxy(typeSpec -> typeSpec.type(ProxyProvider.Proxy.HTTP)
.address(this.httpClientConfig.getProxy().getAddress()));
}
if (LoggerFactory.getLogger(REACTOR_NETWORK_LOG_CATEGORY).isTraceEnabled()) {
this.httpClient = this.httpClient.wiretap(REACTOR_NETWORK_LOG_CATEGORY, LogLevel.INFO);
}
this.httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(configs.getSslContext()))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) configs.getConnectionAcquireTimeout().toMillis())
.httpResponseDecoder(httpResponseDecoderSpec ->
httpResponseDecoderSpec.maxInitialLineLength(configs.getMaxHttpInitialLineLength())
.maxHeaderSize(configs.getMaxHttpHeaderSize())
.maxChunkSize(configs.getMaxHttpChunkSize())
.validateHeaders(true));
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
}
@Override
public Mono<HttpResponse> send(final HttpRequest request, Duration responseTimeout) {
Objects.requireNonNull(request.httpMethod());
Objects.requireNonNull(request.uri());
Objects.requireNonNull(this.httpClientConfig);
if(request.reactorNettyRequestRecord() == null) {
ReactorNettyRequestRecord reactorNettyRequestRecord = new ReactorNettyRequestRecord();
reactorNettyRequestRecord.setTimeCreated(Instant.now());
request.withReactorNettyRequestRecord(reactorNettyRequestRecord);
}
final AtomicReference<ReactorNettyHttpResponse> responseReference = new AtomicReference<>();
return this.httpClient
.keepAlive(this.httpClientConfig.isConnectionKeepAlive())
.port(request.port())
.responseTimeout(responseTimeout)
.request(HttpMethod.valueOf(request.httpMethod().toString()))
.uri(request.uri().toString())
.send(bodySendDelegate(request))
.responseConnection((reactorNettyResponse, reactorNettyConnection) -> {
HttpResponse httpResponse = new ReactorNettyHttpResponse(reactorNettyResponse,
reactorNettyConnection).withRequest(request);
responseReference.set((ReactorNettyHttpResponse) httpResponse);
return Mono.just(httpResponse);
})
.contextWrite(Context.of(REACTOR_NETTY_REQUEST_RECORD_KEY, request.reactorNettyRequestRecord()))
.doOnCancel(() -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.CANCELLED);
}
})
.onErrorMap(throwable -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.ERROR);
}
return throwable;
})
.single();
}
/**
* Delegate to send the request content.
*
* @param restRequest the Rest request contains the body to be sent
* @return a delegate upon invocation sets the request body in reactor-netty outbound object
*/
private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate(final HttpRequest restRequest) {
return (reactorNettyRequest, reactorNettyOutbound) -> {
for (HttpHeader header : restRequest.headers()) {
reactorNettyRequest.header(header.name(), header.value());
}
if (restRequest.body() != null) {
return reactorNettyOutbound.sendByteArray(restRequest.body());
} else {
return reactorNettyOutbound;
}
};
}
@Override
public void shutdown() {
if (this.connectionProvider != null) {
this.connectionProvider.dispose();
}
}
private static ConnectionObserver getConnectionObserver() {
return (conn, state) -> {
Instant time = Instant.now();
if (state.equals(HttpClientState.CONNECTED) || state.equals(HttpClientState.ACQUIRED)) {
if (conn instanceof ConnectionObserver) {
ConnectionObserver observer = (ConnectionObserver) conn;
ReactorNettyRequestRecord requestRecord =
observer.currentContext().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConnected(time);
}
} else if (state.equals(HttpClientState.CONFIGURED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConfigured(time);
}
} else if (state.equals(HttpClientState.REQUEST_SENT)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeSent(time);
}
} else if (state.equals(HttpClientState.RESPONSE_RECEIVED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeReceived(time);
}
}
};
}
private static class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation or error is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation or error happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseOnNotSubscribedResponse(ReactorNettyResponseState reactorNettyResponseState) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, reactorNettyResponseState)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
}
private enum ReactorNettyResponseState {
NOT_SUBSCRIBED,
SUBSCRIBED,
CANCELLED,
ERROR;
}
} | |
> Please let me know what is harm with this approach, also give your exact code, provide perf data base comparison between two approaches. Then i will think over it , otherwise I will keep it as it is are you asking me to write the exact code and perf test the suggested approach Naveen? :-) anyway you can take a look at cross-partition query pipeline where we are parallelizing query to multiple partitions. Over there the code has a lot of other knobs as it needs to be more configurable. Your case is simpler. | public Mono<Void> openConnectionsAndInitCaches() {
Mono<List<FeedRange>> feedRangesMono = this.getFeedRanges();
AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>();
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
return feedRangesMono.flatMap(feedRanges -> {
for (FeedRange feedRange : feedRanges) {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
sequentialList.set(Flux.merge(fluxList).collectList());
return sequentialList.get().flatMap(objects -> Mono.empty());
});
} | List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
My previous question still stand valid "what is harm with this approach". Are you refereeing to drainAsync method in query ? Based on this i see we are using same list with mergeSequential and passing our custome concurrency https://github.com/Azure/azure-sdk-for-java/blob/663620a678dc125339d7dd44d3fdbcb263ca5544/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/ParallelDocumentQueryExecutionContext.java#L388 In this case merge is better the mergeSequential , as we don't need any ordering. And instead of using custom concurrency i would let reactor to handle ` /** * A small default of available slots in a given container, compromise between intensive pipelines, small * subscribers numbers and memory use. */ public static final int SMALL_BUFFER_SIZE = Math.max(16, Integer.parseInt(System.getProperty("reactor.bufferSize.small", "256")));` | public Mono<Void> openConnectionsAndInitCaches() {
Mono<List<FeedRange>> feedRangesMono = this.getFeedRanges();
AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>();
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
return feedRangesMono.flatMap(feedRanges -> {
for (FeedRange feedRange : feedRanges) {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
sequentialList.set(Flux.merge(fluxList).collectList());
return sequentialList.get().flatMap(objects -> Mono.empty());
});
} | List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
Naveen, I added this comment when you had AtomicReference and two lists side by side here this commit: https://github.com/Azure/azure-sdk-for-java/pull/20075/commits/2e75bb277b78f5806cc2d6167fc6cfa98915b974 my comment was more on the AtomicReference and using two lists side by side with custom synchronization logic for ensuring thread safety. I see you addressed part of my comment in a recent commit and removed the custom synchronization AtomicReference: https://github.com/Azure/azure-sdk-for-java/pull/20075/commits/478c60c3c9398e01c746aacae13b7c416276410a The intuition behind why I asked to remove AtomicReference, is to rely more on the reactive-stream functionality. If reactive-stream library is providing a functionality we should try to re-use and not re-invent the same concept. This helps in reducing maintenance cost and make code more readable. after AtomicReference is removed, there is no problem with using `fluxList` just please move its declaration inside the `flatMap`. | public Mono<Void> openConnectionsAndInitCaches() {
Mono<List<FeedRange>> feedRangesMono = this.getFeedRanges();
AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>();
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
return feedRangesMono.flatMap(feedRanges -> {
for (FeedRange feedRange : feedRanges) {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
sequentialList.set(Flux.merge(fluxList).collectList());
return sequentialList.get().flatMap(objects -> Mono.empty());
});
} | List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
Yes I already removed AtomicReference in my previous commit. Also moved fluxList in flat map in a new Iteration. Thanks | public Mono<Void> openConnectionsAndInitCaches() {
Mono<List<FeedRange>> feedRangesMono = this.getFeedRanges();
AtomicReference<Mono<List<FeedResponse<ObjectNode>>>> sequentialList = new AtomicReference<>();
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
return feedRangesMono.flatMap(feedRanges -> {
for (FeedRange feedRange : feedRanges) {
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
if (this.database.getClient().getConnectionPolicy().getConnectionMode().equals(ConnectionMode.DIRECT)) {
options.setConsistencyLevel(ConsistencyLevel.STRONG);
}
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
sequentialList.set(Flux.merge(fluxList).collectList());
return sequentialList.get().flatMap(objects -> Mono.empty());
});
} | List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
Would it make sense to use the merge(fluxList, maxConcurrency) overload to limit concurrency? Or is it ok to just rely on the default (256) https://github.com/reactor/reactor-core/blob/027563ecc803ad3c8afb1420f901870a10def49e/reactor-core/src/main/java/reactor/util/concurrent/Queues.java#L85-L90 | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
Thanks for suggesting . lets go with default first see if we need any fine tune , I went over this before in this conversation https://github.com/Azure/azure-sdk-for-java/pull/20075#discussion_r601786053 | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList(); | public Mono<Void> openConnectionsAndInitCaches() {
if(isInitialized.compareAndSet(false, true)) {
return this.getFeedRanges().flatMap(feedRanges -> {
List<Flux<FeedResponse<ObjectNode>>> fluxList = new ArrayList<>();
SqlQuerySpec querySpec = new SqlQuerySpec();
querySpec.setQueryText("select * from c where c.id = @id");
querySpec.setParameters(Collections.singletonList(new SqlParameter("@id",
UUID.randomUUID().toString())));
for (FeedRange feedRange : feedRanges) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setFeedRange(feedRange);
CosmosPagedFlux<ObjectNode> cosmosPagedFlux = this.queryItems(querySpec, options,
ObjectNode.class);
fluxList.add(cosmosPagedFlux.byPage());
}
Mono<List<FeedResponse<ObjectNode>>> listMono = Flux.merge(fluxList).collectList();
return listMono.flatMap(objects -> Mono.empty());
});
} else {
logger.warn("openConnectionsAndInitCaches is already called once on Container {}, no operation will take place in this call", this.getId());
return Mono.empty();
}
} | class type.
* @return a {@link CosmosPagedFlux} | class type.
* @return a {@link CosmosPagedFlux} |
May not do name replacement for customer in SDK. | public Mono<Void> deleteByNameAsync(String name) {
return this.innerModel().deleteAsync(this.resourceGroupName,
this.namespaceName,
name.replaceAll(Pattern.quote("/"), "~"));
} | name.replaceAll(Pattern.quote("/"), "~")); | public Mono<Void> deleteByNameAsync(String name) {
return this.innerModel().deleteAsync(this.resourceGroupName,
this.namespaceName,
name);
} | class QueuesImpl
extends ServiceBusChildResourcesImpl<
Queue,
QueueImpl,
SBQueueInner,
QueuesClient,
ServiceBusManager,
ServiceBusNamespace>
implements Queues {
private final String resourceGroupName;
private final String namespaceName;
private final Region region;
private final ClientLogger logger = new ClientLogger(QueuesImpl.class);
QueuesImpl(String resourceGroupName, String namespaceName, Region region, ServiceBusManager manager) {
super(manager.serviceClient().getQueues(), manager);
this.resourceGroupName = resourceGroupName;
this.namespaceName = namespaceName;
this.region = region;
}
@Override
public QueueImpl define(String name) {
return wrapModel(name);
}
@Override
@Override
protected Mono<SBQueueInner> getInnerByNameAsync(String name) {
return this.innerModel().getAsync(this.resourceGroupName, this.namespaceName, name);
}
@Override
protected PagedFlux<SBQueueInner> listInnerAsync() {
return this.innerModel().listByNamespaceAsync(this.resourceGroupName, this.namespaceName);
}
@Override
protected PagedIterable<SBQueueInner> listInner() {
return this.innerModel().listByNamespace(this.resourceGroupName, this.namespaceName);
}
@Override
protected QueueImpl wrapModel(String name) {
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
name.replaceAll(Pattern.quote("/"), "~"),
this.region,
new SBQueueInner(),
this.manager());
}
@Override
protected QueueImpl wrapModel(SBQueueInner inner) {
if (inner == null) {
return null;
}
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
inner.name().replaceAll(Pattern.quote("/"), "~"),
this.region,
inner,
this.manager());
}
@Override
public PagedIterable<Queue> listByParent(String resourceGroupName, String parentName) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
@Override
public Mono<Void> deleteByParentAsync(String groupName, String parentName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
@Override
public Mono<Queue> getByParentAsync(String resourceGroup, String parentName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
} | class QueuesImpl
extends ServiceBusChildResourcesImpl<
Queue,
QueueImpl,
SBQueueInner,
QueuesClient,
ServiceBusManager,
ServiceBusNamespace>
implements Queues {
private final String resourceGroupName;
private final String namespaceName;
private final Region region;
private final ClientLogger logger = new ClientLogger(QueuesImpl.class);
QueuesImpl(String resourceGroupName, String namespaceName, Region region, ServiceBusManager manager) {
super(manager.serviceClient().getQueues(), manager);
this.resourceGroupName = resourceGroupName;
this.namespaceName = namespaceName;
this.region = region;
}
@Override
public QueueImpl define(String name) {
return wrapModel(name);
}
@Override
@Override
protected Mono<SBQueueInner> getInnerByNameAsync(String name) {
return this.innerModel().getAsync(this.resourceGroupName, this.namespaceName, name);
}
@Override
protected PagedFlux<SBQueueInner> listInnerAsync() {
return this.innerModel().listByNamespaceAsync(this.resourceGroupName, this.namespaceName);
}
@Override
protected PagedIterable<SBQueueInner> listInner() {
return this.innerModel().listByNamespace(this.resourceGroupName, this.namespaceName);
}
@Override
protected QueueImpl wrapModel(String name) {
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
name,
this.region,
new SBQueueInner(),
this.manager());
}
@Override
protected QueueImpl wrapModel(SBQueueInner inner) {
if (inner == null) {
return null;
}
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
inner.name(),
this.region,
inner,
this.manager());
}
@Override
public PagedIterable<Queue> listByParent(String resourceGroupName, String parentName) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
@Override
public Mono<Void> deleteByParentAsync(String groupName, String parentName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
@Override
public Mono<Queue> getByParentAsync(String resourceGroup, String parentName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
} |
OK. Leave it be. Let user use "~" | public Mono<Void> deleteByNameAsync(String name) {
return this.innerModel().deleteAsync(this.resourceGroupName,
this.namespaceName,
name.replaceAll(Pattern.quote("/"), "~"));
} | name.replaceAll(Pattern.quote("/"), "~")); | public Mono<Void> deleteByNameAsync(String name) {
return this.innerModel().deleteAsync(this.resourceGroupName,
this.namespaceName,
name);
} | class QueuesImpl
extends ServiceBusChildResourcesImpl<
Queue,
QueueImpl,
SBQueueInner,
QueuesClient,
ServiceBusManager,
ServiceBusNamespace>
implements Queues {
private final String resourceGroupName;
private final String namespaceName;
private final Region region;
private final ClientLogger logger = new ClientLogger(QueuesImpl.class);
QueuesImpl(String resourceGroupName, String namespaceName, Region region, ServiceBusManager manager) {
super(manager.serviceClient().getQueues(), manager);
this.resourceGroupName = resourceGroupName;
this.namespaceName = namespaceName;
this.region = region;
}
@Override
public QueueImpl define(String name) {
return wrapModel(name);
}
@Override
@Override
protected Mono<SBQueueInner> getInnerByNameAsync(String name) {
return this.innerModel().getAsync(this.resourceGroupName, this.namespaceName, name);
}
@Override
protected PagedFlux<SBQueueInner> listInnerAsync() {
return this.innerModel().listByNamespaceAsync(this.resourceGroupName, this.namespaceName);
}
@Override
protected PagedIterable<SBQueueInner> listInner() {
return this.innerModel().listByNamespace(this.resourceGroupName, this.namespaceName);
}
@Override
protected QueueImpl wrapModel(String name) {
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
name.replaceAll(Pattern.quote("/"), "~"),
this.region,
new SBQueueInner(),
this.manager());
}
@Override
protected QueueImpl wrapModel(SBQueueInner inner) {
if (inner == null) {
return null;
}
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
inner.name().replaceAll(Pattern.quote("/"), "~"),
this.region,
inner,
this.manager());
}
@Override
public PagedIterable<Queue> listByParent(String resourceGroupName, String parentName) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
@Override
public Mono<Void> deleteByParentAsync(String groupName, String parentName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
@Override
public Mono<Queue> getByParentAsync(String resourceGroup, String parentName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
} | class QueuesImpl
extends ServiceBusChildResourcesImpl<
Queue,
QueueImpl,
SBQueueInner,
QueuesClient,
ServiceBusManager,
ServiceBusNamespace>
implements Queues {
private final String resourceGroupName;
private final String namespaceName;
private final Region region;
private final ClientLogger logger = new ClientLogger(QueuesImpl.class);
QueuesImpl(String resourceGroupName, String namespaceName, Region region, ServiceBusManager manager) {
super(manager.serviceClient().getQueues(), manager);
this.resourceGroupName = resourceGroupName;
this.namespaceName = namespaceName;
this.region = region;
}
@Override
public QueueImpl define(String name) {
return wrapModel(name);
}
@Override
@Override
protected Mono<SBQueueInner> getInnerByNameAsync(String name) {
return this.innerModel().getAsync(this.resourceGroupName, this.namespaceName, name);
}
@Override
protected PagedFlux<SBQueueInner> listInnerAsync() {
return this.innerModel().listByNamespaceAsync(this.resourceGroupName, this.namespaceName);
}
@Override
protected PagedIterable<SBQueueInner> listInner() {
return this.innerModel().listByNamespace(this.resourceGroupName, this.namespaceName);
}
@Override
protected QueueImpl wrapModel(String name) {
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
name,
this.region,
new SBQueueInner(),
this.manager());
}
@Override
protected QueueImpl wrapModel(SBQueueInner inner) {
if (inner == null) {
return null;
}
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
inner.name(),
this.region,
inner,
this.manager());
}
@Override
public PagedIterable<Queue> listByParent(String resourceGroupName, String parentName) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
@Override
public Mono<Void> deleteByParentAsync(String groupName, String parentName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
@Override
public Mono<Queue> getByParentAsync(String resourceGroup, String parentName, String name) {
throw logger.logExceptionAsError(new UnsupportedOperationException());
}
} |
Need a customized `DurationSerializer` to write with nanosecond precision. Else service would think the value being changed, when send back to service. Rest of the code is same as the one in azure-core, which only write with millisecond precision. | public static String toString(Duration duration) {
String result = null;
if (duration != null) {
if (duration.isZero()) {
result = "PT0S";
} else {
final StringBuilder builder = new StringBuilder();
builder.append('P');
final long days = duration.toDays();
if (days > 0) {
builder.append(days);
builder.append('D');
duration = duration.minusDays(days);
}
final long hours = duration.toHours();
if (hours > 0) {
builder.append('T');
builder.append(hours);
builder.append('H');
duration = duration.minusHours(hours);
}
final long minutes = duration.toMinutes();
if (minutes > 0) {
if (hours == 0) {
builder.append('T');
}
builder.append(minutes);
builder.append('M');
duration = duration.minusMinutes(minutes);
}
final long seconds = duration.getSeconds();
if (seconds > 0) {
if (hours == 0 && minutes == 0) {
builder.append('T');
}
builder.append(seconds);
duration = duration.minusSeconds(seconds);
}
long nanoseconds = duration.getNano();
if (nanoseconds > 0) {
if (hours == 0 && minutes == 0 && seconds == 0) {
builder.append("T");
}
if (seconds == 0) {
builder.append("0");
}
builder.append('.');
long nanoMax = 100000000L;
while (nanoseconds < nanoMax) {
builder.append('0');
nanoMax = nanoMax / 10;
}
while (nanoseconds % 10 == 0) {
nanoseconds /= 10;
}
builder.append(nanoseconds);
}
if (seconds > 0 || nanoseconds > 0) {
builder.append('S');
}
result = builder.toString();
}
}
return result;
} | } | public static String toString(Duration duration) {
String result = null;
if (duration != null) {
if (duration.isZero()) {
result = "PT0S";
} else {
final StringBuilder builder = new StringBuilder();
builder.append('P');
final long days = duration.toDays();
if (days > 0) {
builder.append(days);
builder.append('D');
duration = duration.minusDays(days);
}
final long hours = duration.toHours();
if (hours > 0) {
builder.append('T');
builder.append(hours);
builder.append('H');
duration = duration.minusHours(hours);
}
final long minutes = duration.toMinutes();
if (minutes > 0) {
if (hours == 0) {
builder.append('T');
}
builder.append(minutes);
builder.append('M');
duration = duration.minusMinutes(minutes);
}
final long seconds = duration.getSeconds();
if (seconds > 0) {
if (hours == 0 && minutes == 0) {
builder.append('T');
}
builder.append(seconds);
duration = duration.minusSeconds(seconds);
}
long nanoseconds = duration.getNano();
if (nanoseconds > 0) {
if (hours == 0 && minutes == 0 && seconds == 0) {
builder.append("T");
}
if (seconds == 0) {
builder.append("0");
}
builder.append('.');
long nanoMax = 100000000L;
while (nanoseconds < nanoMax) {
builder.append('0');
nanoMax = nanoMax / 10;
}
while (nanoseconds % 10 == 0) {
nanoseconds /= 10;
}
builder.append(nanoseconds);
}
if (seconds > 0 || nanoseconds > 0) {
builder.append('S');
}
result = builder.toString();
}
}
return result;
} | class DurationSerializer extends JsonSerializer<Duration> {
/**
* Gets a module wrapping this serializer as an adapter for the Jackson
* ObjectMapper.
*
* @return a simple module to be plugged onto Jackson ObjectMapper.
*/
public static SimpleModule getModule() {
SimpleModule module = new SimpleModule();
module.addSerializer(Duration.class, new DurationSerializer());
return module;
}
@Override
public void serialize(Duration duration, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeString(DurationSerializer.toString(duration));
}
/**
* Convert to provided Duration to an ISO 8601 String with a days component.
* @param duration The Duration to convert.
* @return The String representation of the provided Duration.
*/
} | class DurationSerializer extends JsonSerializer<Duration> {
/**
* Gets a module wrapping this serializer as an adapter for the Jackson
* ObjectMapper.
*
* @return a simple module to be plugged onto Jackson ObjectMapper.
*/
public static SimpleModule getModule() {
SimpleModule module = new SimpleModule();
module.addSerializer(Duration.class, new DurationSerializer());
return module;
}
@Override
public void serialize(Duration duration, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeString(DurationSerializer.toString(duration));
}
/**
* Convert to provided Duration to an ISO 8601 String with a days component.
* @param duration The Duration to convert.
* @return The String representation of the provided Duration.
*/
} |
Should the `.apply` have the same indent as `.authorizeRequests`? If so, we could add `// @formatter:off` to avoid the IDEA formatting it automatically. | protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.apply(configurer);
} | .apply(configurer); | protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.apply(configurer);
} | class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final AADB2COidcLoginConfigurer configurer;
public WebSecurityConfiguration(AADB2COidcLoginConfigurer configurer) {
this.configurer = configurer;
}
@Override
} | class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final AADB2COidcLoginConfigurer configurer;
public WebSecurityConfiguration(AADB2COidcLoginConfigurer configurer) {
this.configurer = configurer;
}
@Override
} |
isn't `byPage` smart enough to deal with optional parameters ? | PagedFlux<FileSystemItem> listFileSystemsWithOptionalTimeout(ListFileSystemsOptions options, Duration timeout) {
PagedFlux<BlobContainerItem> inputPagedFlux = blobServiceAsyncClient
.listBlobContainers(Transforms.toListBlobContainersOptions(options));
/* We need to create a new PagedFlux here because PagedFlux extends Flux, but not all operations were
overriden to return PagedFlux - so we need to do the transformations and recreate a PagedFlux. */
return StoragePagedFlux.create(() -> (continuationToken, pageSize) -> {
Flux<PagedResponse<BlobContainerItem>> flux;
if (continuationToken != null && pageSize != null) {
flux = inputPagedFlux.byPage(continuationToken, pageSize);
} else if (continuationToken != null) {
flux = inputPagedFlux.byPage(continuationToken);
} else if (pageSize != null) {
flux = inputPagedFlux.byPage(pageSize);
} else {
flux = inputPagedFlux.byPage();
}
flux = flux.onErrorMap(DataLakeImplUtils::transformBlobStorageException);
if (timeout != null) {
flux = flux.timeout(timeout);
}
return flux
.map(blobsPagedResponse -> new PagedResponseBase<Void, FileSystemItem>(
blobsPagedResponse.getRequest(),
blobsPagedResponse.getStatusCode(),
blobsPagedResponse.getHeaders(),
blobsPagedResponse
.getValue()
.stream()
.map(Transforms::toFileSystemItem).collect(Collectors.toList()),
blobsPagedResponse.getContinuationToken(),
null));
});
} | flux = inputPagedFlux.byPage(continuationToken, pageSize); | PagedFlux<FileSystemItem> listFileSystemsWithOptionalTimeout(ListFileSystemsOptions options, Duration timeout) {
PagedFlux<BlobContainerItem> inputPagedFlux = blobServiceAsyncClient
.listBlobContainers(Transforms.toListBlobContainersOptions(options));
/* We need to create a new PagedFlux here because PagedFlux extends Flux, but not all operations were
overriden to return PagedFlux - so we need to do the transformations and recreate a PagedFlux. */
return PagedFlux.create(() -> (continuationToken, pageSize) -> {
Flux<PagedResponse<BlobContainerItem>> flux;
if (continuationToken != null && pageSize != null) {
flux = inputPagedFlux.byPage(continuationToken, pageSize);
} else if (continuationToken != null) {
flux = inputPagedFlux.byPage(continuationToken);
} else if (pageSize != null) {
flux = inputPagedFlux.byPage(pageSize);
} else {
flux = inputPagedFlux.byPage();
}
flux = flux.onErrorMap(DataLakeImplUtils::transformBlobStorageException);
if (timeout != null) {
flux = flux.timeout(timeout);
}
return flux
.map(blobsPagedResponse -> new PagedResponseBase<Void, FileSystemItem>(
blobsPagedResponse.getRequest(),
blobsPagedResponse.getStatusCode(),
blobsPagedResponse.getHeaders(),
blobsPagedResponse
.getValue()
.stream()
.map(Transforms::toFileSystemItem).collect(Collectors.toList()),
blobsPagedResponse.getContinuationToken(),
null));
});
} | class DataLakeServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(DataLakeServiceAsyncClient.class);
private final DataLakeStorageClientImpl azureDataLakeStorage;
private final String accountName;
private final DataLakeServiceVersion serviceVersion;
private final BlobServiceAsyncClient blobServiceAsyncClient;
/**
* Package-private constructor for use by {@link DataLakeServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param blobServiceAsyncClient The underlying {@link BlobServiceAsyncClient}
*/
DataLakeServiceAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion,
String accountName, BlobServiceAsyncClient blobServiceAsyncClient) {
this.azureDataLakeStorage = new DataLakeStorageClientBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.build();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.blobServiceAsyncClient = blobServiceAsyncClient;
}
/**
* Initializes a {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system. This method
* does not create a file system. It simply constructs the URL to the file system and offers access to methods
* relevant to file systems.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getFileSystemAsyncClient
*
* @param fileSystemName The name of the file system to point to. A value of null or empty string will be
* interpreted as pointing to the root file system and will be replaced by "$root".
* @return A {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system
*/
public DataLakeFileSystemAsyncClient getFileSystemAsyncClient(String fileSystemName) {
if (CoreUtils.isNullOrEmpty(fileSystemName)) {
fileSystemName = DataLakeFileSystemAsyncClient.ROOT_FILESYSTEM_NAME;
}
return new DataLakeFileSystemAsyncClient(getHttpPipeline(),
StorageImplUtils.appendToUrlPath(getAccountUrl(), Utility.urlEncode(Utility.urlDecode(fileSystemName)))
.toString(), getServiceVersion(), getAccountName(), fileSystemName,
blobServiceAsyncClient.getBlobContainerAsyncClient(fileSystemName)
);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureDataLakeStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public DataLakeServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new file system within a storage account. If a file system with the same name already exists, the
* operation fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystem
*
* @param fileSystemName Name of the file system to create
* @return A {@link Mono} containing a {@link DataLakeFileSystemAsyncClient} used to interact with the file system
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileSystemAsyncClient> createFileSystem(String fileSystemName) {
try {
return createFileSystemWithResponse(fileSystemName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new file system within a storage account. If a file system with the same name already exists, the
* operation fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystemWithResponse
*
* @param fileSystemName Name of the file system to create
* @param metadata Metadata to associate with the file system. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this file system is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileSystemAsyncClient} used to interact with the file system created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileSystemAsyncClient>> createFileSystemWithResponse(String fileSystemName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
DataLakeFileSystemAsyncClient dataLakeFileSystemAsyncClient = getFileSystemAsyncClient(fileSystemName);
return dataLakeFileSystemAsyncClient.createWithResponse(metadata, accessType).
map(response -> new SimpleResponse<>(response, dataLakeFileSystemAsyncClient));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystem
*
* @param fileSystemName Name of the file system to delete
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFileSystem(String fileSystemName) {
try {
return deleteFileSystemWithResponse(fileSystemName, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystemWithResponse
*
* @param fileSystemName Name of the file system to delete
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileSystemWithResponse(String fileSystemName,
DataLakeRequestConditions requestConditions) {
try {
return getFileSystemAsyncClient(fileSystemName).deleteWithResponse(requestConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureDataLakeStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems}
*
* @return A reactive response emitting the list of file systems.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FileSystemItem> listFileSystems() {
try {
return this.listFileSystems(new ListFileSystemsOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems
*
* @param options A {@link ListFileSystemsOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of file systems.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FileSystemItem> listFileSystems(ListFileSystemsOptions options) {
try {
return listFileSystemsWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
* when using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return this.getUserDelegationKeyWithResponse(start, expiry).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
* when using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return blobServiceAsyncClient.getUserDelegationKeyWithResponse(start, expiry)
.onErrorMap(DataLakeImplUtils::transformBlobStorageException)
.map(response ->
new SimpleResponse<>(response, Transforms.toDataLakeUserDelegationKey(response.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to file
* systems and file shares.</p>
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return blobServiceAsyncClient.generateAccountSas(accountSasSignatureValues);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to file
* systems and file shares.</p>
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
return blobServiceAsyncClient.generateAccountSas(accountSasSignatureValues, context);
}
/**
* Restores a previously deleted file system.
* If the file system associated with provided <code>deletedFileSystemName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the file system.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.undeleteFileSystem
*
* @param deletedFileSystemName The name of the previously deleted file system.
* @param deletedFileSystemVersion The version of the previously deleted file system.
* @return A {@link Mono} containing a {@link DataLakeFileSystemAsyncClient} used
* to interact with the restored file system.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileSystemAsyncClient> undeleteFileSystem(
String deletedFileSystemName, String deletedFileSystemVersion) {
return this.undeleteFileSystemWithResponse(new FileSystemUndeleteOptions(deletedFileSystemName,
deletedFileSystemVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted file system. The restored file system
* will be renamed to the <code>destinationFileSystemName</code> if provided in <code>options</code>.
* Otherwise <code>deletedFileSystemName</code> is used as he destination file system name.
* If the file system associated with provided <code>destinationFileSystemName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled for the storage account associated with the
* file system.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.undeleteFileSystemWithResponse
*
* @param options {@link FileSystemUndeleteOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileSystemAsyncClient} used to interact with the restored file system.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileSystemAsyncClient>> undeleteFileSystemWithResponse(
FileSystemUndeleteOptions options) {
try {
return blobServiceAsyncClient.undeleteBlobContainerWithResponse(
Transforms.toBlobContainerUndeleteOptions(options))
.onErrorMap(DataLakeImplUtils::transformBlobStorageException)
.map(response -> new SimpleResponse<>(response, getFileSystemAsyncClient(response.getValue()
.getBlobContainerName())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} | class DataLakeServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(DataLakeServiceAsyncClient.class);
private final AzureDataLakeStorageRestAPIImpl azureDataLakeStorage;
private final String accountName;
private final DataLakeServiceVersion serviceVersion;
private final BlobServiceAsyncClient blobServiceAsyncClient;
/**
* Package-private constructor for use by {@link DataLakeServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param blobServiceAsyncClient The underlying {@link BlobServiceAsyncClient}
*/
DataLakeServiceAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion,
String accountName, BlobServiceAsyncClient blobServiceAsyncClient) {
this.azureDataLakeStorage = new AzureDataLakeStorageRestAPIImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.blobServiceAsyncClient = blobServiceAsyncClient;
}
/**
* Initializes a {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system. This method
* does not create a file system. It simply constructs the URL to the file system and offers access to methods
* relevant to file systems.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getFileSystemAsyncClient
*
* @param fileSystemName The name of the file system to point to. A value of null or empty string will be
* interpreted as pointing to the root file system and will be replaced by "$root".
* @return A {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system
*/
public DataLakeFileSystemAsyncClient getFileSystemAsyncClient(String fileSystemName) {
if (CoreUtils.isNullOrEmpty(fileSystemName)) {
fileSystemName = DataLakeFileSystemAsyncClient.ROOT_FILESYSTEM_NAME;
}
return new DataLakeFileSystemAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), fileSystemName, blobServiceAsyncClient.getBlobContainerAsyncClient(fileSystemName));
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureDataLakeStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public DataLakeServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new file system within a storage account. If a file system with the same name already exists, the
* operation fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystem
*
* @param fileSystemName Name of the file system to create
* @return A {@link Mono} containing a {@link DataLakeFileSystemAsyncClient} used to interact with the file system
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileSystemAsyncClient> createFileSystem(String fileSystemName) {
try {
return createFileSystemWithResponse(fileSystemName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new file system within a storage account. If a file system with the same name already exists, the
* operation fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystemWithResponse
*
* @param fileSystemName Name of the file system to create
* @param metadata Metadata to associate with the file system. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this file system is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileSystemAsyncClient} used to interact with the file system created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileSystemAsyncClient>> createFileSystemWithResponse(String fileSystemName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
DataLakeFileSystemAsyncClient dataLakeFileSystemAsyncClient = getFileSystemAsyncClient(fileSystemName);
return dataLakeFileSystemAsyncClient.createWithResponse(metadata, accessType).
map(response -> new SimpleResponse<>(response, dataLakeFileSystemAsyncClient));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystem
*
* @param fileSystemName Name of the file system to delete
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFileSystem(String fileSystemName) {
try {
return deleteFileSystemWithResponse(fileSystemName, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystemWithResponse
*
* @param fileSystemName Name of the file system to delete
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileSystemWithResponse(String fileSystemName,
DataLakeRequestConditions requestConditions) {
try {
return getFileSystemAsyncClient(fileSystemName).deleteWithResponse(requestConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureDataLakeStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems}
*
* @return A reactive response emitting the list of file systems.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FileSystemItem> listFileSystems() {
try {
return this.listFileSystems(new ListFileSystemsOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems
*
* @param options A {@link ListFileSystemsOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of file systems.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FileSystemItem> listFileSystems(ListFileSystemsOptions options) {
try {
return listFileSystemsWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
* when using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return this.getUserDelegationKeyWithResponse(start, expiry).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
* when using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return blobServiceAsyncClient.getUserDelegationKeyWithResponse(start, expiry)
.onErrorMap(DataLakeImplUtils::transformBlobStorageException)
.map(response ->
new SimpleResponse<>(response, Transforms.toDataLakeUserDelegationKey(response.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to file
* systems and file shares.</p>
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return blobServiceAsyncClient.generateAccountSas(accountSasSignatureValues);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to file
* systems and file shares.</p>
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
return blobServiceAsyncClient.generateAccountSas(accountSasSignatureValues, context);
}
/**
* Restores a previously deleted file system.
* If the file system associated with provided <code>deletedFileSystemName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the file system.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.undeleteFileSystem
*
* @param deletedFileSystemName The name of the previously deleted file system.
* @param deletedFileSystemVersion The version of the previously deleted file system.
* @return A {@link Mono} containing a {@link DataLakeFileSystemAsyncClient} used
* to interact with the restored file system.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileSystemAsyncClient> undeleteFileSystem(
String deletedFileSystemName, String deletedFileSystemVersion) {
return this.undeleteFileSystemWithResponse(new FileSystemUndeleteOptions(deletedFileSystemName,
deletedFileSystemVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted file system. The restored file system
* will be renamed to the <code>destinationFileSystemName</code> if provided in <code>options</code>.
* Otherwise <code>deletedFileSystemName</code> is used as he destination file system name.
* If the file system associated with provided <code>destinationFileSystemName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled for the storage account associated with the
* file system.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.undeleteFileSystemWithResponse
*
* @param options {@link FileSystemUndeleteOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileSystemAsyncClient} used to interact with the restored file system.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileSystemAsyncClient>> undeleteFileSystemWithResponse(
FileSystemUndeleteOptions options) {
try {
return blobServiceAsyncClient.undeleteBlobContainerWithResponse(
Transforms.toBlobContainerUndeleteOptions(options))
.onErrorMap(DataLakeImplUtils::transformBlobStorageException)
.map(response -> new SimpleResponse<>(response, getFileSystemAsyncClient(response.getValue()
.getBlobContainerName())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} |
Is there a reason why `FindBlobsOptions` can no longer be null? Or did this throw an NPE if null previously and is being triggered sooner? | PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
options.setMaxResultsPerPage(pageSize);
return withContext(context -> this.findBlobsByTags(options, marker, timeout, context));
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
} | StorageImplUtils.assertNotNull("options", options); | PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> withContext(context -> this.findBlobsByTags(
new FindBlobsOptions(options.getQuery()).setMaxResultsPerPage(pageSize), marker, timeout, context));
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
} | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
private final String accountName;
private final BlobServiceVersion serviceVersion;
private final CpkInfo customerProvidedKey;
private final EncryptionScope encryptionScope;
private final BlobContainerEncryptionScope blobContainerEncryptionScope;
private final boolean anonymousAccess;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param anonymousAccess Whether or not the client was built with anonymousAccess
*/
BlobServiceAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
CpkInfo customerProvidedKey, EncryptionScope encryptionScope,
BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) {
/* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer
when the sas token has already been applied. */
try {
URI.create(url);
} catch (IllegalArgumentException ex) {
throw logger.logExceptionAsError(ex);
}
this.azureBlobStorage = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.customerProvidedKey = customerProvidedKey;
this.encryptionScope = encryptionScope;
this.blobContainerEncryptionScope = blobContainerEncryptionScope;
this.anonymousAccess = anonymousAccess;
}
/**
* Initializes a {@link BlobContainerAsyncClient} object pointing to the specified container. This method does not
* create a container. It simply constructs the URL to the container and offers access to methods relevant to
* containers.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient
*
* @param containerName The name of the container to point to. A value of null or empty string will be interpreted
* as pointing to the root container and will be replaced by "$root".
* @return A {@link BlobContainerAsyncClient} object pointing to the specified container
*/
public BlobContainerAsyncClient getBlobContainerAsyncClient(String containerName) {
if (CoreUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
return new BlobContainerAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer
*
* @param containerName Name of the container to create
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> createBlobContainer(String containerName) {
try {
return createBlobContainerWithResponse(containerName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse
*
* @param containerName Name of the container to create
* @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this container is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
return withContext(context -> createBlobContainerWithResponse(containerName, metadata, accessType,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType, Context context) {
throwOnAnonymousAccess();
BlobContainerAsyncClient blobContainerAsyncClient = getBlobContainerAsyncClient(containerName);
return blobContainerAsyncClient.createWithResponse(metadata, accessType, context)
.map(response -> new SimpleResponse<>(response, blobContainerAsyncClient));
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlobContainer(String containerName) {
try {
return deleteBlobContainerWithResponse(containerName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName) {
try {
return withContext(context -> deleteBlobContainerWithResponse(containerName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName, Context context) {
throwOnAnonymousAccess();
return getBlobContainerAsyncClient(containerName).deleteWithResponse(null, context);
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureBlobStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers}
*
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers() {
try {
return this.listBlobContainers(new ListBlobContainersOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers
*
* @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options) {
try {
return listBlobContainersWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<BlobContainerItem> listBlobContainersWithOptionalTimeout(ListBlobContainersOptions options,
Duration timeout) {
throwOnAnonymousAccess();
BiFunction<String, Integer, Mono<PagedResponse<BlobContainerItem>>> func =
(marker, pageSize) -> {
ListBlobContainersOptions finalOptions = null;
if (pageSize != null) {
if (options == null) {
finalOptions = new ListBlobContainersOptions().setMaxResultsPerPage(pageSize);
} else {
finalOptions = options.setMaxResultsPerPage(pageSize);
}
}
return listBlobContainersSegment(marker, finalOptions, timeout);
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<BlobContainerItem>> listBlobContainersSegment(String marker,
ListBlobContainersOptions options, Duration timeout) {
options = options == null ? new ListBlobContainersOptions() : options;
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().listBlobContainersSegmentSinglePageAsync(
options.getPrefix(), marker, options.getMaxResultsPerPage(),
toIncludeTypes(options.getDetails()),
null, null, Context.NONE), timeout);
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag
*
* @param query Filters the results to return only blobs whose tags match the specified expression.
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(String query) {
return this.findBlobsByTags(new FindBlobsOptions(query));
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag
*
* @param options {@link FindBlobsOptions}
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options) {
try {
return findBlobsByTags(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
options.setMaxResultsPerPage(pageSize);
return this.findBlobsByTags(options, marker, timeout, context);
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<TaggedBlobItem>> findBlobsByTags(
FindBlobsOptions options, String marker,
Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().filterBlobsWithResponseAsync(null, null,
options.getQuery(), marker, options.getMaxResultsPerPage(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)), timeout)
.map(response -> {
List<TaggedBlobItem> value = response.getValue().getBlobs() == null
? Collections.emptyList()
: response.getValue().getBlobs().stream()
.map(ModelHelper::populateTaggedBlobItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getValue().getNextMarker(),
response.getDeserializedHeaders());
});
}
/**
* Converts {@link BlobContainerListDetails} into list of {@link ListBlobContainersIncludeType}
* that contains only options selected. If no option is selected then null is returned.
*
* @return a list of selected options converted into {@link ListBlobContainersIncludeType}, null if none
* of options has been selected.
*/
private List<ListBlobContainersIncludeType> toIncludeTypes(BlobContainerListDetails blobContainerListDetails) {
boolean hasDetails = blobContainerListDetails != null
&& (blobContainerListDetails.getRetrieveMetadata() || blobContainerListDetails.getRetrieveDeleted());
if (hasDetails) {
List<ListBlobContainersIncludeType> flags = new ArrayList<>(2);
if (blobContainerListDetails.getRetrieveDeleted()) {
flags.add(ListBlobContainersIncludeType.DELETED);
}
if (blobContainerListDetails.getRetrieveMetadata()) {
flags.add(ListBlobContainersIncludeType.METADATA);
}
return flags;
} else {
return null;
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getProperties}
*
* @return A reactive response containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceProperties> getProperties() {
try {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceProperties>> getPropertiesWithResponse() {
try {
return withContext(this::getPropertiesWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceProperties>> getPropertiesWithResponse(Context context) {
context = context == null ? Context.NONE : context;
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getPropertiesWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setProperties
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(BlobServiceProperties properties) {
try {
return setPropertiesWithResponse(properties).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties) {
try {
return withContext(context -> setPropertiesWithResponse(properties, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties, Context context) {
throwOnAnonymousAccess();
BlobServiceProperties finalProperties = null;
if (properties != null) {
finalProperties = new BlobServiceProperties();
finalProperties.setLogging(properties.getLogging());
if (finalProperties.getLogging() != null) {
StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion());
validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy");
}
finalProperties.setHourMetrics(properties.getHourMetrics());
if (finalProperties.getHourMetrics() != null) {
StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion());
validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention "
+ "Policy");
if (finalProperties.getHourMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("HourMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
finalProperties.setMinuteMetrics(properties.getMinuteMetrics());
if (finalProperties.getMinuteMetrics() != null) {
StorageImplUtils.assertNotNull("MinuteMetrics Version",
finalProperties.getMinuteMetrics().getVersion());
validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics "
+ "Retention Policy");
if (finalProperties.getMinuteMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
if (properties.getCors() != null) {
List<BlobCorsRule> corsRules = new ArrayList<>();
for (BlobCorsRule rule : properties.getCors()) {
corsRules.add(validatedCorsRule(rule));
}
finalProperties.setCors(corsRules);
}
finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion());
finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy());
validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days");
finalProperties.setStaticWebsite(properties.getStaticWebsite());
}
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().setPropertiesWithResponseAsync(finalProperties, null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Sets any null fields to "" since the service requires all Cors rules to be set if some are set.
* @param originalRule {@link BlobCorsRule}
* @return The validated {@link BlobCorsRule}
*/
private BlobCorsRule validatedCorsRule(BlobCorsRule originalRule) {
if (originalRule == null) {
return null;
}
BlobCorsRule validRule = new BlobCorsRule();
validRule.setAllowedHeaders(StorageImplUtils.emptyIfNull(originalRule.getAllowedHeaders()));
validRule.setAllowedMethods(StorageImplUtils.emptyIfNull(originalRule.getAllowedMethods()));
validRule.setAllowedOrigins(StorageImplUtils.emptyIfNull(originalRule.getAllowedOrigins()));
validRule.setExposedHeaders(StorageImplUtils.emptyIfNull(originalRule.getExposedHeaders()));
validRule.setMaxAgeInSeconds(originalRule.getMaxAgeInSeconds());
return validRule;
}
/**
* Validates a {@link BlobRetentionPolicy} according to service specs for set properties.
* @param retentionPolicy {@link BlobRetentionPolicy}
* @param policyName The name of the variable for errors.
*/
private void validateRetentionPolicy(BlobRetentionPolicy retentionPolicy, String policyName) {
if (retentionPolicy == null) {
return;
}
if (retentionPolicy.isEnabled()) {
StorageImplUtils.assertInBounds(policyName, retentionPolicy.getDays(), 1, 365);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry,
Context context) {
StorageImplUtils.assertNotNull("expiry", expiry);
if (start != null && !start.isBefore(expiry)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("`start` must be null or a datetime before `expiry`."));
}
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getUserDelegationKeyWithResponseAsync(
new KeyInfo()
.setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start))
.setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)),
null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatistics}
*
* @return A {@link Mono} containing the storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceStatistics> getStatistics() {
try {
return getStatisticsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse() {
try {
return withContext(this::getStatisticsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse(Context context) {
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getStatisticsWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo}
*
* @return A {@link Mono} containing containing the storage account info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getAccountInfoWithResponseAsync(context)
.map(rb -> {
ServicesGetAccountInfoHeaders hd = rb.getDeserializedHeaders();
return new SimpleResponse<>(rb, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind()));
});
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return generateAccountSas(accountSasSignatureValues, Context.NONE);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
throwOnAnonymousAccess();
return new AccountSasImplUtil(accountSasSignatureValues)
.generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context);
}
/**
* Checks if service client was built with credentials.
*/
private void throwOnAnonymousAccess() {
if (anonymousAccess) {
throw logger.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without "
+ "credentials"));
}
}
/**
* Restores a previously deleted container.
* If the container associated with provided <code>deletedContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer
*
* @param deletedContainerName The name of the previously deleted container.
* @param deletedContainerVersion The version of the previously deleted container.
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used
* to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> undeleteBlobContainer(
String deletedContainerName, String deletedContainerVersion) {
return this.undeleteBlobContainerWithResponse(new UndeleteBlobContainerOptions(deletedContainerName,
deletedContainerVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted container. The restored container
* will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>.
* Otherwise <code>deletedContainerName</code> is used as destination container name.
* If the container associated with provided <code>destinationContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse
*
* @param options {@link UndeleteBlobContainerOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options) {
try {
return withContext(context -> undeleteBlobContainerWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null;
String finalDestinationContainerName =
hasOptionalDestinationContainerName ? options.getDestinationContainerName()
: options.getDeletedContainerName();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getContainers().restoreWithResponseAsync(finalDestinationContainerName, null,
null, options.getDeletedContainerName(), options.getDeletedContainerVersion(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response,
getBlobContainerAsyncClient(finalDestinationContainerName)));
}
} | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
private final String accountName;
private final BlobServiceVersion serviceVersion;
private final CpkInfo customerProvidedKey;
private final EncryptionScope encryptionScope;
private final BlobContainerEncryptionScope blobContainerEncryptionScope;
private final boolean anonymousAccess;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param anonymousAccess Whether or not the client was built with anonymousAccess
*/
BlobServiceAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
CpkInfo customerProvidedKey, EncryptionScope encryptionScope,
BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) {
/* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer
when the sas token has already been applied. */
try {
URI.create(url);
} catch (IllegalArgumentException ex) {
throw logger.logExceptionAsError(ex);
}
this.azureBlobStorage = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.customerProvidedKey = customerProvidedKey;
this.encryptionScope = encryptionScope;
this.blobContainerEncryptionScope = blobContainerEncryptionScope;
this.anonymousAccess = anonymousAccess;
}
/**
* Initializes a {@link BlobContainerAsyncClient} object pointing to the specified container. This method does not
* create a container. It simply constructs the URL to the container and offers access to methods relevant to
* containers.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient
*
* @param containerName The name of the container to point to. A value of null or empty string will be interpreted
* as pointing to the root container and will be replaced by "$root".
* @return A {@link BlobContainerAsyncClient} object pointing to the specified container
*/
public BlobContainerAsyncClient getBlobContainerAsyncClient(String containerName) {
if (CoreUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
return new BlobContainerAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer
*
* @param containerName Name of the container to create
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> createBlobContainer(String containerName) {
try {
return createBlobContainerWithResponse(containerName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse
*
* @param containerName Name of the container to create
* @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this container is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
return withContext(context -> createBlobContainerWithResponse(containerName, metadata, accessType,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType, Context context) {
throwOnAnonymousAccess();
BlobContainerAsyncClient blobContainerAsyncClient = getBlobContainerAsyncClient(containerName);
return blobContainerAsyncClient.createWithResponse(metadata, accessType, context)
.map(response -> new SimpleResponse<>(response, blobContainerAsyncClient));
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlobContainer(String containerName) {
try {
return deleteBlobContainerWithResponse(containerName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName) {
try {
return withContext(context -> deleteBlobContainerWithResponse(containerName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName, Context context) {
throwOnAnonymousAccess();
return getBlobContainerAsyncClient(containerName).deleteWithResponse(null, context);
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureBlobStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers}
*
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers() {
try {
return this.listBlobContainers(new ListBlobContainersOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers
*
* @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options) {
try {
return listBlobContainersWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<BlobContainerItem> listBlobContainersWithOptionalTimeout(ListBlobContainersOptions options,
Duration timeout) {
throwOnAnonymousAccess();
BiFunction<String, Integer, Mono<PagedResponse<BlobContainerItem>>> func =
(marker, pageSize) -> {
ListBlobContainersOptions finalOptions;
if (pageSize != null) {
if (options == null) {
finalOptions = new ListBlobContainersOptions().setMaxResultsPerPage(pageSize);
} else {
finalOptions = new ListBlobContainersOptions()
.setMaxResultsPerPage(pageSize)
.setDetails(options.getDetails())
.setPrefix(options.getPrefix());
}
} else {
finalOptions = options;
}
return listBlobContainersSegment(marker, finalOptions, timeout);
};
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<BlobContainerItem>> listBlobContainersSegment(String marker,
ListBlobContainersOptions options, Duration timeout) {
options = options == null ? new ListBlobContainersOptions() : options;
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().listBlobContainersSegmentSinglePageAsync(
options.getPrefix(), marker, options.getMaxResultsPerPage(),
toIncludeTypes(options.getDetails()),
null, null, Context.NONE), timeout);
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag
*
* @param query Filters the results to return only blobs whose tags match the specified expression.
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(String query) {
return this.findBlobsByTags(new FindBlobsOptions(query));
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag
*
* @param options {@link FindBlobsOptions}
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options) {
try {
return findBlobsByTags(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
FindBlobsOptions finalOptions;
if (pageSize != null) {
finalOptions = new FindBlobsOptions(options.getQuery())
.setMaxResultsPerPage(pageSize);
} else {
finalOptions = options;
}
return this.findBlobsByTags(finalOptions, marker, timeout, context);
};
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<TaggedBlobItem>> findBlobsByTags(
FindBlobsOptions options, String marker,
Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().filterBlobsWithResponseAsync(null, null,
options.getQuery(), marker, options.getMaxResultsPerPage(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)), timeout)
.map(response -> {
List<TaggedBlobItem> value = response.getValue().getBlobs() == null
? Collections.emptyList()
: response.getValue().getBlobs().stream()
.map(ModelHelper::populateTaggedBlobItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getValue().getNextMarker(),
response.getDeserializedHeaders());
});
}
/**
* Converts {@link BlobContainerListDetails} into list of {@link ListBlobContainersIncludeType}
* that contains only options selected. If no option is selected then null is returned.
*
* @return a list of selected options converted into {@link ListBlobContainersIncludeType}, null if none
* of options has been selected.
*/
private List<ListBlobContainersIncludeType> toIncludeTypes(BlobContainerListDetails blobContainerListDetails) {
boolean hasDetails = blobContainerListDetails != null
&& (blobContainerListDetails.getRetrieveMetadata() || blobContainerListDetails.getRetrieveDeleted());
if (hasDetails) {
List<ListBlobContainersIncludeType> flags = new ArrayList<>(2);
if (blobContainerListDetails.getRetrieveDeleted()) {
flags.add(ListBlobContainersIncludeType.DELETED);
}
if (blobContainerListDetails.getRetrieveMetadata()) {
flags.add(ListBlobContainersIncludeType.METADATA);
}
return flags;
} else {
return null;
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getProperties}
*
* @return A reactive response containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceProperties> getProperties() {
try {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceProperties>> getPropertiesWithResponse() {
try {
return withContext(this::getPropertiesWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceProperties>> getPropertiesWithResponse(Context context) {
context = context == null ? Context.NONE : context;
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getPropertiesWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setProperties
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(BlobServiceProperties properties) {
try {
return setPropertiesWithResponse(properties).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties) {
try {
return withContext(context -> setPropertiesWithResponse(properties, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties, Context context) {
throwOnAnonymousAccess();
BlobServiceProperties finalProperties = null;
if (properties != null) {
finalProperties = new BlobServiceProperties();
finalProperties.setLogging(properties.getLogging());
if (finalProperties.getLogging() != null) {
StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion());
validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy");
}
finalProperties.setHourMetrics(properties.getHourMetrics());
if (finalProperties.getHourMetrics() != null) {
StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion());
validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention "
+ "Policy");
if (finalProperties.getHourMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("HourMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
finalProperties.setMinuteMetrics(properties.getMinuteMetrics());
if (finalProperties.getMinuteMetrics() != null) {
StorageImplUtils.assertNotNull("MinuteMetrics Version",
finalProperties.getMinuteMetrics().getVersion());
validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics "
+ "Retention Policy");
if (finalProperties.getMinuteMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
if (properties.getCors() != null) {
List<BlobCorsRule> corsRules = new ArrayList<>();
for (BlobCorsRule rule : properties.getCors()) {
corsRules.add(validatedCorsRule(rule));
}
finalProperties.setCors(corsRules);
}
finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion());
finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy());
validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days");
finalProperties.setStaticWebsite(properties.getStaticWebsite());
}
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().setPropertiesWithResponseAsync(finalProperties, null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Sets any null fields to "" since the service requires all Cors rules to be set if some are set.
* @param originalRule {@link BlobCorsRule}
* @return The validated {@link BlobCorsRule}
*/
private BlobCorsRule validatedCorsRule(BlobCorsRule originalRule) {
if (originalRule == null) {
return null;
}
BlobCorsRule validRule = new BlobCorsRule();
validRule.setAllowedHeaders(StorageImplUtils.emptyIfNull(originalRule.getAllowedHeaders()));
validRule.setAllowedMethods(StorageImplUtils.emptyIfNull(originalRule.getAllowedMethods()));
validRule.setAllowedOrigins(StorageImplUtils.emptyIfNull(originalRule.getAllowedOrigins()));
validRule.setExposedHeaders(StorageImplUtils.emptyIfNull(originalRule.getExposedHeaders()));
validRule.setMaxAgeInSeconds(originalRule.getMaxAgeInSeconds());
return validRule;
}
/**
* Validates a {@link BlobRetentionPolicy} according to service specs for set properties.
* @param retentionPolicy {@link BlobRetentionPolicy}
* @param policyName The name of the variable for errors.
*/
private void validateRetentionPolicy(BlobRetentionPolicy retentionPolicy, String policyName) {
if (retentionPolicy == null) {
return;
}
if (retentionPolicy.isEnabled()) {
StorageImplUtils.assertInBounds(policyName, retentionPolicy.getDays(), 1, 365);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry,
Context context) {
StorageImplUtils.assertNotNull("expiry", expiry);
if (start != null && !start.isBefore(expiry)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("`start` must be null or a datetime before `expiry`."));
}
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getUserDelegationKeyWithResponseAsync(
new KeyInfo()
.setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start))
.setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)),
null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatistics}
*
* @return A {@link Mono} containing the storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceStatistics> getStatistics() {
try {
return getStatisticsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse() {
try {
return withContext(this::getStatisticsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse(Context context) {
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getStatisticsWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo}
*
* @return A {@link Mono} containing containing the storage account info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getAccountInfoWithResponseAsync(context)
.map(rb -> {
ServicesGetAccountInfoHeaders hd = rb.getDeserializedHeaders();
return new SimpleResponse<>(rb, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind()));
});
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return generateAccountSas(accountSasSignatureValues, Context.NONE);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
throwOnAnonymousAccess();
return new AccountSasImplUtil(accountSasSignatureValues)
.generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context);
}
/**
* Checks if service client was built with credentials.
*/
private void throwOnAnonymousAccess() {
if (anonymousAccess) {
throw logger.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without "
+ "credentials"));
}
}
/**
* Restores a previously deleted container.
* If the container associated with provided <code>deletedContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer
*
* @param deletedContainerName The name of the previously deleted container.
* @param deletedContainerVersion The version of the previously deleted container.
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used
* to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> undeleteBlobContainer(
String deletedContainerName, String deletedContainerVersion) {
return this.undeleteBlobContainerWithResponse(new UndeleteBlobContainerOptions(deletedContainerName,
deletedContainerVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted container. The restored container
* will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>.
* Otherwise <code>deletedContainerName</code> is used as destination container name.
* If the container associated with provided <code>destinationContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse
*
* @param options {@link UndeleteBlobContainerOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options) {
try {
return withContext(context -> undeleteBlobContainerWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null;
String finalDestinationContainerName =
hasOptionalDestinationContainerName ? options.getDestinationContainerName()
: options.getDeletedContainerName();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getContainers().restoreWithResponseAsync(finalDestinationContainerName, null,
null, options.getDeletedContainerName(), options.getDeletedContainerVersion(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response,
getBlobContainerAsyncClient(finalDestinationContainerName)));
}
} |
No. If you pass a null continuationToken, it short circuits and returns an empty flux. We need to specifically use the overload which matches the values we have | PagedFlux<FileSystemItem> listFileSystemsWithOptionalTimeout(ListFileSystemsOptions options, Duration timeout) {
PagedFlux<BlobContainerItem> inputPagedFlux = blobServiceAsyncClient
.listBlobContainers(Transforms.toListBlobContainersOptions(options));
/* We need to create a new PagedFlux here because PagedFlux extends Flux, but not all operations were
overriden to return PagedFlux - so we need to do the transformations and recreate a PagedFlux. */
return StoragePagedFlux.create(() -> (continuationToken, pageSize) -> {
Flux<PagedResponse<BlobContainerItem>> flux;
if (continuationToken != null && pageSize != null) {
flux = inputPagedFlux.byPage(continuationToken, pageSize);
} else if (continuationToken != null) {
flux = inputPagedFlux.byPage(continuationToken);
} else if (pageSize != null) {
flux = inputPagedFlux.byPage(pageSize);
} else {
flux = inputPagedFlux.byPage();
}
flux = flux.onErrorMap(DataLakeImplUtils::transformBlobStorageException);
if (timeout != null) {
flux = flux.timeout(timeout);
}
return flux
.map(blobsPagedResponse -> new PagedResponseBase<Void, FileSystemItem>(
blobsPagedResponse.getRequest(),
blobsPagedResponse.getStatusCode(),
blobsPagedResponse.getHeaders(),
blobsPagedResponse
.getValue()
.stream()
.map(Transforms::toFileSystemItem).collect(Collectors.toList()),
blobsPagedResponse.getContinuationToken(),
null));
});
} | flux = inputPagedFlux.byPage(continuationToken, pageSize); | PagedFlux<FileSystemItem> listFileSystemsWithOptionalTimeout(ListFileSystemsOptions options, Duration timeout) {
PagedFlux<BlobContainerItem> inputPagedFlux = blobServiceAsyncClient
.listBlobContainers(Transforms.toListBlobContainersOptions(options));
/* We need to create a new PagedFlux here because PagedFlux extends Flux, but not all operations were
overriden to return PagedFlux - so we need to do the transformations and recreate a PagedFlux. */
return PagedFlux.create(() -> (continuationToken, pageSize) -> {
Flux<PagedResponse<BlobContainerItem>> flux;
if (continuationToken != null && pageSize != null) {
flux = inputPagedFlux.byPage(continuationToken, pageSize);
} else if (continuationToken != null) {
flux = inputPagedFlux.byPage(continuationToken);
} else if (pageSize != null) {
flux = inputPagedFlux.byPage(pageSize);
} else {
flux = inputPagedFlux.byPage();
}
flux = flux.onErrorMap(DataLakeImplUtils::transformBlobStorageException);
if (timeout != null) {
flux = flux.timeout(timeout);
}
return flux
.map(blobsPagedResponse -> new PagedResponseBase<Void, FileSystemItem>(
blobsPagedResponse.getRequest(),
blobsPagedResponse.getStatusCode(),
blobsPagedResponse.getHeaders(),
blobsPagedResponse
.getValue()
.stream()
.map(Transforms::toFileSystemItem).collect(Collectors.toList()),
blobsPagedResponse.getContinuationToken(),
null));
});
} | class DataLakeServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(DataLakeServiceAsyncClient.class);
private final DataLakeStorageClientImpl azureDataLakeStorage;
private final String accountName;
private final DataLakeServiceVersion serviceVersion;
private final BlobServiceAsyncClient blobServiceAsyncClient;
/**
* Package-private constructor for use by {@link DataLakeServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param blobServiceAsyncClient The underlying {@link BlobServiceAsyncClient}
*/
DataLakeServiceAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion,
String accountName, BlobServiceAsyncClient blobServiceAsyncClient) {
this.azureDataLakeStorage = new DataLakeStorageClientBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.build();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.blobServiceAsyncClient = blobServiceAsyncClient;
}
/**
* Initializes a {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system. This method
* does not create a file system. It simply constructs the URL to the file system and offers access to methods
* relevant to file systems.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getFileSystemAsyncClient
*
* @param fileSystemName The name of the file system to point to. A value of null or empty string will be
* interpreted as pointing to the root file system and will be replaced by "$root".
* @return A {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system
*/
public DataLakeFileSystemAsyncClient getFileSystemAsyncClient(String fileSystemName) {
if (CoreUtils.isNullOrEmpty(fileSystemName)) {
fileSystemName = DataLakeFileSystemAsyncClient.ROOT_FILESYSTEM_NAME;
}
return new DataLakeFileSystemAsyncClient(getHttpPipeline(),
StorageImplUtils.appendToUrlPath(getAccountUrl(), Utility.urlEncode(Utility.urlDecode(fileSystemName)))
.toString(), getServiceVersion(), getAccountName(), fileSystemName,
blobServiceAsyncClient.getBlobContainerAsyncClient(fileSystemName)
);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureDataLakeStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public DataLakeServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new file system within a storage account. If a file system with the same name already exists, the
* operation fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystem
*
* @param fileSystemName Name of the file system to create
* @return A {@link Mono} containing a {@link DataLakeFileSystemAsyncClient} used to interact with the file system
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileSystemAsyncClient> createFileSystem(String fileSystemName) {
try {
return createFileSystemWithResponse(fileSystemName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new file system within a storage account. If a file system with the same name already exists, the
* operation fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystemWithResponse
*
* @param fileSystemName Name of the file system to create
* @param metadata Metadata to associate with the file system. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this file system is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileSystemAsyncClient} used to interact with the file system created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileSystemAsyncClient>> createFileSystemWithResponse(String fileSystemName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
DataLakeFileSystemAsyncClient dataLakeFileSystemAsyncClient = getFileSystemAsyncClient(fileSystemName);
return dataLakeFileSystemAsyncClient.createWithResponse(metadata, accessType).
map(response -> new SimpleResponse<>(response, dataLakeFileSystemAsyncClient));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystem
*
* @param fileSystemName Name of the file system to delete
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFileSystem(String fileSystemName) {
try {
return deleteFileSystemWithResponse(fileSystemName, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystemWithResponse
*
* @param fileSystemName Name of the file system to delete
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileSystemWithResponse(String fileSystemName,
DataLakeRequestConditions requestConditions) {
try {
return getFileSystemAsyncClient(fileSystemName).deleteWithResponse(requestConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureDataLakeStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems}
*
* @return A reactive response emitting the list of file systems.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FileSystemItem> listFileSystems() {
try {
return this.listFileSystems(new ListFileSystemsOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems
*
* @param options A {@link ListFileSystemsOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of file systems.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FileSystemItem> listFileSystems(ListFileSystemsOptions options) {
try {
return listFileSystemsWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
* when using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return this.getUserDelegationKeyWithResponse(start, expiry).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
* when using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return blobServiceAsyncClient.getUserDelegationKeyWithResponse(start, expiry)
.onErrorMap(DataLakeImplUtils::transformBlobStorageException)
.map(response ->
new SimpleResponse<>(response, Transforms.toDataLakeUserDelegationKey(response.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to file
* systems and file shares.</p>
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return blobServiceAsyncClient.generateAccountSas(accountSasSignatureValues);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to file
* systems and file shares.</p>
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
return blobServiceAsyncClient.generateAccountSas(accountSasSignatureValues, context);
}
/**
* Restores a previously deleted file system.
* If the file system associated with provided <code>deletedFileSystemName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the file system.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.undeleteFileSystem
*
* @param deletedFileSystemName The name of the previously deleted file system.
* @param deletedFileSystemVersion The version of the previously deleted file system.
* @return A {@link Mono} containing a {@link DataLakeFileSystemAsyncClient} used
* to interact with the restored file system.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileSystemAsyncClient> undeleteFileSystem(
String deletedFileSystemName, String deletedFileSystemVersion) {
return this.undeleteFileSystemWithResponse(new FileSystemUndeleteOptions(deletedFileSystemName,
deletedFileSystemVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted file system. The restored file system
* will be renamed to the <code>destinationFileSystemName</code> if provided in <code>options</code>.
* Otherwise <code>deletedFileSystemName</code> is used as he destination file system name.
* If the file system associated with provided <code>destinationFileSystemName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled for the storage account associated with the
* file system.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.undeleteFileSystemWithResponse
*
* @param options {@link FileSystemUndeleteOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileSystemAsyncClient} used to interact with the restored file system.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileSystemAsyncClient>> undeleteFileSystemWithResponse(
FileSystemUndeleteOptions options) {
try {
return blobServiceAsyncClient.undeleteBlobContainerWithResponse(
Transforms.toBlobContainerUndeleteOptions(options))
.onErrorMap(DataLakeImplUtils::transformBlobStorageException)
.map(response -> new SimpleResponse<>(response, getFileSystemAsyncClient(response.getValue()
.getBlobContainerName())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} | class DataLakeServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(DataLakeServiceAsyncClient.class);
private final AzureDataLakeStorageRestAPIImpl azureDataLakeStorage;
private final String accountName;
private final DataLakeServiceVersion serviceVersion;
private final BlobServiceAsyncClient blobServiceAsyncClient;
/**
* Package-private constructor for use by {@link DataLakeServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param blobServiceAsyncClient The underlying {@link BlobServiceAsyncClient}
*/
DataLakeServiceAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion,
String accountName, BlobServiceAsyncClient blobServiceAsyncClient) {
this.azureDataLakeStorage = new AzureDataLakeStorageRestAPIImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.blobServiceAsyncClient = blobServiceAsyncClient;
}
/**
* Initializes a {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system. This method
* does not create a file system. It simply constructs the URL to the file system and offers access to methods
* relevant to file systems.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getFileSystemAsyncClient
*
* @param fileSystemName The name of the file system to point to. A value of null or empty string will be
* interpreted as pointing to the root file system and will be replaced by "$root".
* @return A {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system
*/
public DataLakeFileSystemAsyncClient getFileSystemAsyncClient(String fileSystemName) {
if (CoreUtils.isNullOrEmpty(fileSystemName)) {
fileSystemName = DataLakeFileSystemAsyncClient.ROOT_FILESYSTEM_NAME;
}
return new DataLakeFileSystemAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), fileSystemName, blobServiceAsyncClient.getBlobContainerAsyncClient(fileSystemName));
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureDataLakeStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public DataLakeServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new file system within a storage account. If a file system with the same name already exists, the
* operation fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystem
*
* @param fileSystemName Name of the file system to create
* @return A {@link Mono} containing a {@link DataLakeFileSystemAsyncClient} used to interact with the file system
* created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileSystemAsyncClient> createFileSystem(String fileSystemName) {
try {
return createFileSystemWithResponse(fileSystemName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new file system within a storage account. If a file system with the same name already exists, the
* operation fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystemWithResponse
*
* @param fileSystemName Name of the file system to create
* @param metadata Metadata to associate with the file system. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this file system is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileSystemAsyncClient} used to interact with the file system created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileSystemAsyncClient>> createFileSystemWithResponse(String fileSystemName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
DataLakeFileSystemAsyncClient dataLakeFileSystemAsyncClient = getFileSystemAsyncClient(fileSystemName);
return dataLakeFileSystemAsyncClient.createWithResponse(metadata, accessType).
map(response -> new SimpleResponse<>(response, dataLakeFileSystemAsyncClient));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystem
*
* @param fileSystemName Name of the file system to delete
* @return A reactive response signalling completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteFileSystem(String fileSystemName) {
try {
return deleteFileSystemWithResponse(fileSystemName, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
* For more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystemWithResponse
*
* @param fileSystemName Name of the file system to delete
* @param requestConditions {@link DataLakeRequestConditions}
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteFileSystemWithResponse(String fileSystemName,
DataLakeRequestConditions requestConditions) {
try {
return getFileSystemAsyncClient(fileSystemName).deleteWithResponse(requestConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureDataLakeStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems}
*
* @return A reactive response emitting the list of file systems.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FileSystemItem> listFileSystems() {
try {
return this.listFileSystems(new ListFileSystemsOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
* information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems
*
* @param options A {@link ListFileSystemsOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of file systems.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FileSystemItem> listFileSystems(ListFileSystemsOptions options) {
try {
return listFileSystemsWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
* when using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return this.getUserDelegationKeyWithResponse(start, expiry).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
* when using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return blobServiceAsyncClient.getUserDelegationKeyWithResponse(start, expiry)
.onErrorMap(DataLakeImplUtils::transformBlobStorageException)
.map(response ->
new SimpleResponse<>(response, Transforms.toDataLakeUserDelegationKey(response.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to file
* systems and file shares.</p>
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return blobServiceAsyncClient.generateAccountSas(accountSasSignatureValues);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to file
* systems and file shares.</p>
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
return blobServiceAsyncClient.generateAccountSas(accountSasSignatureValues, context);
}
/**
* Restores a previously deleted file system.
* If the file system associated with provided <code>deletedFileSystemName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the file system.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.undeleteFileSystem
*
* @param deletedFileSystemName The name of the previously deleted file system.
* @param deletedFileSystemVersion The version of the previously deleted file system.
* @return A {@link Mono} containing a {@link DataLakeFileSystemAsyncClient} used
* to interact with the restored file system.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataLakeFileSystemAsyncClient> undeleteFileSystem(
String deletedFileSystemName, String deletedFileSystemVersion) {
return this.undeleteFileSystemWithResponse(new FileSystemUndeleteOptions(deletedFileSystemName,
deletedFileSystemVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted file system. The restored file system
* will be renamed to the <code>destinationFileSystemName</code> if provided in <code>options</code>.
* Otherwise <code>deletedFileSystemName</code> is used as he destination file system name.
* If the file system associated with provided <code>destinationFileSystemName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled for the storage account associated with the
* file system.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.undeleteFileSystemWithResponse
*
* @param options {@link FileSystemUndeleteOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DataLakeFileSystemAsyncClient} used to interact with the restored file system.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataLakeFileSystemAsyncClient>> undeleteFileSystemWithResponse(
FileSystemUndeleteOptions options) {
try {
return blobServiceAsyncClient.undeleteBlobContainerWithResponse(
Transforms.toBlobContainerUndeleteOptions(options))
.onErrorMap(DataLakeImplUtils::transformBlobStorageException)
.map(response -> new SimpleResponse<>(response, getFileSystemAsyncClient(response.getValue()
.getBlobContainerName())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} |
Should we create a new options here? | PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
options.setMaxResultsPerPage(pageSize);
return withContext(context -> this.findBlobsByTags(options, marker, timeout, context));
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
} | options.setMaxResultsPerPage(pageSize); | PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> withContext(context -> this.findBlobsByTags(
new FindBlobsOptions(options.getQuery()).setMaxResultsPerPage(pageSize), marker, timeout, context));
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
} | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
private final String accountName;
private final BlobServiceVersion serviceVersion;
private final CpkInfo customerProvidedKey;
private final EncryptionScope encryptionScope;
private final BlobContainerEncryptionScope blobContainerEncryptionScope;
private final boolean anonymousAccess;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param anonymousAccess Whether or not the client was built with anonymousAccess
*/
BlobServiceAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
CpkInfo customerProvidedKey, EncryptionScope encryptionScope,
BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) {
/* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer
when the sas token has already been applied. */
try {
URI.create(url);
} catch (IllegalArgumentException ex) {
throw logger.logExceptionAsError(ex);
}
this.azureBlobStorage = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.customerProvidedKey = customerProvidedKey;
this.encryptionScope = encryptionScope;
this.blobContainerEncryptionScope = blobContainerEncryptionScope;
this.anonymousAccess = anonymousAccess;
}
/**
* Initializes a {@link BlobContainerAsyncClient} object pointing to the specified container. This method does not
* create a container. It simply constructs the URL to the container and offers access to methods relevant to
* containers.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient
*
* @param containerName The name of the container to point to. A value of null or empty string will be interpreted
* as pointing to the root container and will be replaced by "$root".
* @return A {@link BlobContainerAsyncClient} object pointing to the specified container
*/
public BlobContainerAsyncClient getBlobContainerAsyncClient(String containerName) {
if (CoreUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
return new BlobContainerAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer
*
* @param containerName Name of the container to create
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> createBlobContainer(String containerName) {
try {
return createBlobContainerWithResponse(containerName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse
*
* @param containerName Name of the container to create
* @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this container is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
return withContext(context -> createBlobContainerWithResponse(containerName, metadata, accessType,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType, Context context) {
throwOnAnonymousAccess();
BlobContainerAsyncClient blobContainerAsyncClient = getBlobContainerAsyncClient(containerName);
return blobContainerAsyncClient.createWithResponse(metadata, accessType, context)
.map(response -> new SimpleResponse<>(response, blobContainerAsyncClient));
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlobContainer(String containerName) {
try {
return deleteBlobContainerWithResponse(containerName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName) {
try {
return withContext(context -> deleteBlobContainerWithResponse(containerName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName, Context context) {
throwOnAnonymousAccess();
return getBlobContainerAsyncClient(containerName).deleteWithResponse(null, context);
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureBlobStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers}
*
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers() {
try {
return this.listBlobContainers(new ListBlobContainersOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers
*
* @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options) {
try {
return listBlobContainersWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<BlobContainerItem> listBlobContainersWithOptionalTimeout(ListBlobContainersOptions options,
Duration timeout) {
throwOnAnonymousAccess();
BiFunction<String, Integer, Mono<PagedResponse<BlobContainerItem>>> func =
(marker, pageSize) -> {
ListBlobContainersOptions finalOptions = null;
if (pageSize != null) {
if (options == null) {
finalOptions = new ListBlobContainersOptions().setMaxResultsPerPage(pageSize);
} else {
finalOptions = new ListBlobContainersOptions()
.setMaxResultsPerPage(pageSize)
.setDetails(options.getDetails())
.setPrefix(options.getPrefix());
}
}
return listBlobContainersSegment(marker, finalOptions, timeout);
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<BlobContainerItem>> listBlobContainersSegment(String marker,
ListBlobContainersOptions options, Duration timeout) {
options = options == null ? new ListBlobContainersOptions() : options;
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().listBlobContainersSegmentSinglePageAsync(
options.getPrefix(), marker, options.getMaxResultsPerPage(),
toIncludeTypes(options.getDetails()),
null, null, Context.NONE), timeout);
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag
*
* @param query Filters the results to return only blobs whose tags match the specified expression.
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(String query) {
return this.findBlobsByTags(new FindBlobsOptions(query));
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag
*
* @param options {@link FindBlobsOptions}
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options) {
try {
return findBlobsByTags(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
FindBlobsOptions finalOptions;
if (pageSize != null) {
finalOptions = new FindBlobsOptions(options.getQuery())
.setMaxResultsPerPage(pageSize);
} else {
finalOptions = options;
}
return this.findBlobsByTags(finalOptions, marker, timeout, context);
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<TaggedBlobItem>> findBlobsByTags(
FindBlobsOptions options, String marker,
Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().filterBlobsWithResponseAsync(null, null,
options.getQuery(), marker, options.getMaxResultsPerPage(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)), timeout)
.map(response -> {
List<TaggedBlobItem> value = response.getValue().getBlobs() == null
? Collections.emptyList()
: response.getValue().getBlobs().stream()
.map(ModelHelper::populateTaggedBlobItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getValue().getNextMarker(),
response.getDeserializedHeaders());
});
}
/**
* Converts {@link BlobContainerListDetails} into list of {@link ListBlobContainersIncludeType}
* that contains only options selected. If no option is selected then null is returned.
*
* @return a list of selected options converted into {@link ListBlobContainersIncludeType}, null if none
* of options has been selected.
*/
private List<ListBlobContainersIncludeType> toIncludeTypes(BlobContainerListDetails blobContainerListDetails) {
boolean hasDetails = blobContainerListDetails != null
&& (blobContainerListDetails.getRetrieveMetadata() || blobContainerListDetails.getRetrieveDeleted());
if (hasDetails) {
List<ListBlobContainersIncludeType> flags = new ArrayList<>(2);
if (blobContainerListDetails.getRetrieveDeleted()) {
flags.add(ListBlobContainersIncludeType.DELETED);
}
if (blobContainerListDetails.getRetrieveMetadata()) {
flags.add(ListBlobContainersIncludeType.METADATA);
}
return flags;
} else {
return null;
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getProperties}
*
* @return A reactive response containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceProperties> getProperties() {
try {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceProperties>> getPropertiesWithResponse() {
try {
return withContext(this::getPropertiesWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceProperties>> getPropertiesWithResponse(Context context) {
context = context == null ? Context.NONE : context;
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getPropertiesWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setProperties
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(BlobServiceProperties properties) {
try {
return setPropertiesWithResponse(properties).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties) {
try {
return withContext(context -> setPropertiesWithResponse(properties, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties, Context context) {
throwOnAnonymousAccess();
BlobServiceProperties finalProperties = null;
if (properties != null) {
finalProperties = new BlobServiceProperties();
finalProperties.setLogging(properties.getLogging());
if (finalProperties.getLogging() != null) {
StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion());
validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy");
}
finalProperties.setHourMetrics(properties.getHourMetrics());
if (finalProperties.getHourMetrics() != null) {
StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion());
validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention "
+ "Policy");
if (finalProperties.getHourMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("HourMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
finalProperties.setMinuteMetrics(properties.getMinuteMetrics());
if (finalProperties.getMinuteMetrics() != null) {
StorageImplUtils.assertNotNull("MinuteMetrics Version",
finalProperties.getMinuteMetrics().getVersion());
validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics "
+ "Retention Policy");
if (finalProperties.getMinuteMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
if (properties.getCors() != null) {
List<BlobCorsRule> corsRules = new ArrayList<>();
for (BlobCorsRule rule : properties.getCors()) {
corsRules.add(validatedCorsRule(rule));
}
finalProperties.setCors(corsRules);
}
finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion());
finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy());
validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days");
finalProperties.setStaticWebsite(properties.getStaticWebsite());
}
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().setPropertiesWithResponseAsync(finalProperties, null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Sets any null fields to "" since the service requires all Cors rules to be set if some are set.
* @param originalRule {@link BlobCorsRule}
* @return The validated {@link BlobCorsRule}
*/
private BlobCorsRule validatedCorsRule(BlobCorsRule originalRule) {
if (originalRule == null) {
return null;
}
BlobCorsRule validRule = new BlobCorsRule();
validRule.setAllowedHeaders(StorageImplUtils.emptyIfNull(originalRule.getAllowedHeaders()));
validRule.setAllowedMethods(StorageImplUtils.emptyIfNull(originalRule.getAllowedMethods()));
validRule.setAllowedOrigins(StorageImplUtils.emptyIfNull(originalRule.getAllowedOrigins()));
validRule.setExposedHeaders(StorageImplUtils.emptyIfNull(originalRule.getExposedHeaders()));
validRule.setMaxAgeInSeconds(originalRule.getMaxAgeInSeconds());
return validRule;
}
/**
* Validates a {@link BlobRetentionPolicy} according to service specs for set properties.
* @param retentionPolicy {@link BlobRetentionPolicy}
* @param policyName The name of the variable for errors.
*/
private void validateRetentionPolicy(BlobRetentionPolicy retentionPolicy, String policyName) {
if (retentionPolicy == null) {
return;
}
if (retentionPolicy.isEnabled()) {
StorageImplUtils.assertInBounds(policyName, retentionPolicy.getDays(), 1, 365);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry,
Context context) {
StorageImplUtils.assertNotNull("expiry", expiry);
if (start != null && !start.isBefore(expiry)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("`start` must be null or a datetime before `expiry`."));
}
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getUserDelegationKeyWithResponseAsync(
new KeyInfo()
.setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start))
.setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)),
null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatistics}
*
* @return A {@link Mono} containing the storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceStatistics> getStatistics() {
try {
return getStatisticsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse() {
try {
return withContext(this::getStatisticsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse(Context context) {
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getStatisticsWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo}
*
* @return A {@link Mono} containing containing the storage account info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getAccountInfoWithResponseAsync(context)
.map(rb -> {
ServicesGetAccountInfoHeaders hd = rb.getDeserializedHeaders();
return new SimpleResponse<>(rb, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind()));
});
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return generateAccountSas(accountSasSignatureValues, Context.NONE);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
throwOnAnonymousAccess();
return new AccountSasImplUtil(accountSasSignatureValues)
.generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context);
}
/**
* Checks if service client was built with credentials.
*/
private void throwOnAnonymousAccess() {
if (anonymousAccess) {
throw logger.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without "
+ "credentials"));
}
}
/**
* Restores a previously deleted container.
* If the container associated with provided <code>deletedContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer
*
* @param deletedContainerName The name of the previously deleted container.
* @param deletedContainerVersion The version of the previously deleted container.
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used
* to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> undeleteBlobContainer(
String deletedContainerName, String deletedContainerVersion) {
return this.undeleteBlobContainerWithResponse(new UndeleteBlobContainerOptions(deletedContainerName,
deletedContainerVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted container. The restored container
* will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>.
* Otherwise <code>deletedContainerName</code> is used as destination container name.
* If the container associated with provided <code>destinationContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse
*
* @param options {@link UndeleteBlobContainerOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options) {
try {
return withContext(context -> undeleteBlobContainerWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null;
String finalDestinationContainerName =
hasOptionalDestinationContainerName ? options.getDestinationContainerName()
: options.getDeletedContainerName();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getContainers().restoreWithResponseAsync(finalDestinationContainerName, null,
null, options.getDeletedContainerName(), options.getDeletedContainerVersion(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response,
getBlobContainerAsyncClient(finalDestinationContainerName)));
}
} | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
private final String accountName;
private final BlobServiceVersion serviceVersion;
private final CpkInfo customerProvidedKey;
private final EncryptionScope encryptionScope;
private final BlobContainerEncryptionScope blobContainerEncryptionScope;
private final boolean anonymousAccess;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param anonymousAccess Whether or not the client was built with anonymousAccess
*/
BlobServiceAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
CpkInfo customerProvidedKey, EncryptionScope encryptionScope,
BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) {
/* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer
when the sas token has already been applied. */
try {
URI.create(url);
} catch (IllegalArgumentException ex) {
throw logger.logExceptionAsError(ex);
}
this.azureBlobStorage = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.customerProvidedKey = customerProvidedKey;
this.encryptionScope = encryptionScope;
this.blobContainerEncryptionScope = blobContainerEncryptionScope;
this.anonymousAccess = anonymousAccess;
}
/**
* Initializes a {@link BlobContainerAsyncClient} object pointing to the specified container. This method does not
* create a container. It simply constructs the URL to the container and offers access to methods relevant to
* containers.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient
*
* @param containerName The name of the container to point to. A value of null or empty string will be interpreted
* as pointing to the root container and will be replaced by "$root".
* @return A {@link BlobContainerAsyncClient} object pointing to the specified container
*/
public BlobContainerAsyncClient getBlobContainerAsyncClient(String containerName) {
if (CoreUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
return new BlobContainerAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer
*
* @param containerName Name of the container to create
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> createBlobContainer(String containerName) {
try {
return createBlobContainerWithResponse(containerName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse
*
* @param containerName Name of the container to create
* @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this container is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
return withContext(context -> createBlobContainerWithResponse(containerName, metadata, accessType,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType, Context context) {
throwOnAnonymousAccess();
BlobContainerAsyncClient blobContainerAsyncClient = getBlobContainerAsyncClient(containerName);
return blobContainerAsyncClient.createWithResponse(metadata, accessType, context)
.map(response -> new SimpleResponse<>(response, blobContainerAsyncClient));
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlobContainer(String containerName) {
try {
return deleteBlobContainerWithResponse(containerName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName) {
try {
return withContext(context -> deleteBlobContainerWithResponse(containerName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName, Context context) {
throwOnAnonymousAccess();
return getBlobContainerAsyncClient(containerName).deleteWithResponse(null, context);
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureBlobStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers}
*
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers() {
try {
return this.listBlobContainers(new ListBlobContainersOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers
*
* @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options) {
try {
return listBlobContainersWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<BlobContainerItem> listBlobContainersWithOptionalTimeout(ListBlobContainersOptions options,
Duration timeout) {
throwOnAnonymousAccess();
BiFunction<String, Integer, Mono<PagedResponse<BlobContainerItem>>> func =
(marker, pageSize) -> {
ListBlobContainersOptions finalOptions;
if (pageSize != null) {
if (options == null) {
finalOptions = new ListBlobContainersOptions().setMaxResultsPerPage(pageSize);
} else {
finalOptions = new ListBlobContainersOptions()
.setMaxResultsPerPage(pageSize)
.setDetails(options.getDetails())
.setPrefix(options.getPrefix());
}
} else {
finalOptions = options;
}
return listBlobContainersSegment(marker, finalOptions, timeout);
};
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<BlobContainerItem>> listBlobContainersSegment(String marker,
ListBlobContainersOptions options, Duration timeout) {
options = options == null ? new ListBlobContainersOptions() : options;
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().listBlobContainersSegmentSinglePageAsync(
options.getPrefix(), marker, options.getMaxResultsPerPage(),
toIncludeTypes(options.getDetails()),
null, null, Context.NONE), timeout);
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag
*
* @param query Filters the results to return only blobs whose tags match the specified expression.
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(String query) {
return this.findBlobsByTags(new FindBlobsOptions(query));
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag
*
* @param options {@link FindBlobsOptions}
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options) {
try {
return findBlobsByTags(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
FindBlobsOptions finalOptions;
if (pageSize != null) {
finalOptions = new FindBlobsOptions(options.getQuery())
.setMaxResultsPerPage(pageSize);
} else {
finalOptions = options;
}
return this.findBlobsByTags(finalOptions, marker, timeout, context);
};
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<TaggedBlobItem>> findBlobsByTags(
FindBlobsOptions options, String marker,
Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().filterBlobsWithResponseAsync(null, null,
options.getQuery(), marker, options.getMaxResultsPerPage(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)), timeout)
.map(response -> {
List<TaggedBlobItem> value = response.getValue().getBlobs() == null
? Collections.emptyList()
: response.getValue().getBlobs().stream()
.map(ModelHelper::populateTaggedBlobItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getValue().getNextMarker(),
response.getDeserializedHeaders());
});
}
/**
* Converts {@link BlobContainerListDetails} into list of {@link ListBlobContainersIncludeType}
* that contains only options selected. If no option is selected then null is returned.
*
* @return a list of selected options converted into {@link ListBlobContainersIncludeType}, null if none
* of options has been selected.
*/
private List<ListBlobContainersIncludeType> toIncludeTypes(BlobContainerListDetails blobContainerListDetails) {
boolean hasDetails = blobContainerListDetails != null
&& (blobContainerListDetails.getRetrieveMetadata() || blobContainerListDetails.getRetrieveDeleted());
if (hasDetails) {
List<ListBlobContainersIncludeType> flags = new ArrayList<>(2);
if (blobContainerListDetails.getRetrieveDeleted()) {
flags.add(ListBlobContainersIncludeType.DELETED);
}
if (blobContainerListDetails.getRetrieveMetadata()) {
flags.add(ListBlobContainersIncludeType.METADATA);
}
return flags;
} else {
return null;
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getProperties}
*
* @return A reactive response containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceProperties> getProperties() {
try {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceProperties>> getPropertiesWithResponse() {
try {
return withContext(this::getPropertiesWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceProperties>> getPropertiesWithResponse(Context context) {
context = context == null ? Context.NONE : context;
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getPropertiesWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setProperties
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(BlobServiceProperties properties) {
try {
return setPropertiesWithResponse(properties).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties) {
try {
return withContext(context -> setPropertiesWithResponse(properties, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties, Context context) {
throwOnAnonymousAccess();
BlobServiceProperties finalProperties = null;
if (properties != null) {
finalProperties = new BlobServiceProperties();
finalProperties.setLogging(properties.getLogging());
if (finalProperties.getLogging() != null) {
StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion());
validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy");
}
finalProperties.setHourMetrics(properties.getHourMetrics());
if (finalProperties.getHourMetrics() != null) {
StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion());
validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention "
+ "Policy");
if (finalProperties.getHourMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("HourMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
finalProperties.setMinuteMetrics(properties.getMinuteMetrics());
if (finalProperties.getMinuteMetrics() != null) {
StorageImplUtils.assertNotNull("MinuteMetrics Version",
finalProperties.getMinuteMetrics().getVersion());
validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics "
+ "Retention Policy");
if (finalProperties.getMinuteMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
if (properties.getCors() != null) {
List<BlobCorsRule> corsRules = new ArrayList<>();
for (BlobCorsRule rule : properties.getCors()) {
corsRules.add(validatedCorsRule(rule));
}
finalProperties.setCors(corsRules);
}
finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion());
finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy());
validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days");
finalProperties.setStaticWebsite(properties.getStaticWebsite());
}
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().setPropertiesWithResponseAsync(finalProperties, null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Sets any null fields to "" since the service requires all Cors rules to be set if some are set.
* @param originalRule {@link BlobCorsRule}
* @return The validated {@link BlobCorsRule}
*/
private BlobCorsRule validatedCorsRule(BlobCorsRule originalRule) {
if (originalRule == null) {
return null;
}
BlobCorsRule validRule = new BlobCorsRule();
validRule.setAllowedHeaders(StorageImplUtils.emptyIfNull(originalRule.getAllowedHeaders()));
validRule.setAllowedMethods(StorageImplUtils.emptyIfNull(originalRule.getAllowedMethods()));
validRule.setAllowedOrigins(StorageImplUtils.emptyIfNull(originalRule.getAllowedOrigins()));
validRule.setExposedHeaders(StorageImplUtils.emptyIfNull(originalRule.getExposedHeaders()));
validRule.setMaxAgeInSeconds(originalRule.getMaxAgeInSeconds());
return validRule;
}
/**
* Validates a {@link BlobRetentionPolicy} according to service specs for set properties.
* @param retentionPolicy {@link BlobRetentionPolicy}
* @param policyName The name of the variable for errors.
*/
private void validateRetentionPolicy(BlobRetentionPolicy retentionPolicy, String policyName) {
if (retentionPolicy == null) {
return;
}
if (retentionPolicy.isEnabled()) {
StorageImplUtils.assertInBounds(policyName, retentionPolicy.getDays(), 1, 365);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry,
Context context) {
StorageImplUtils.assertNotNull("expiry", expiry);
if (start != null && !start.isBefore(expiry)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("`start` must be null or a datetime before `expiry`."));
}
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getUserDelegationKeyWithResponseAsync(
new KeyInfo()
.setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start))
.setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)),
null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatistics}
*
* @return A {@link Mono} containing the storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceStatistics> getStatistics() {
try {
return getStatisticsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse() {
try {
return withContext(this::getStatisticsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse(Context context) {
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getStatisticsWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo}
*
* @return A {@link Mono} containing containing the storage account info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getAccountInfoWithResponseAsync(context)
.map(rb -> {
ServicesGetAccountInfoHeaders hd = rb.getDeserializedHeaders();
return new SimpleResponse<>(rb, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind()));
});
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return generateAccountSas(accountSasSignatureValues, Context.NONE);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
throwOnAnonymousAccess();
return new AccountSasImplUtil(accountSasSignatureValues)
.generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context);
}
/**
* Checks if service client was built with credentials.
*/
private void throwOnAnonymousAccess() {
if (anonymousAccess) {
throw logger.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without "
+ "credentials"));
}
}
/**
* Restores a previously deleted container.
* If the container associated with provided <code>deletedContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer
*
* @param deletedContainerName The name of the previously deleted container.
* @param deletedContainerVersion The version of the previously deleted container.
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used
* to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> undeleteBlobContainer(
String deletedContainerName, String deletedContainerVersion) {
return this.undeleteBlobContainerWithResponse(new UndeleteBlobContainerOptions(deletedContainerName,
deletedContainerVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted container. The restored container
* will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>.
* Otherwise <code>deletedContainerName</code> is used as destination container name.
* If the container associated with provided <code>destinationContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse
*
* @param options {@link UndeleteBlobContainerOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options) {
try {
return withContext(context -> undeleteBlobContainerWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null;
String finalDestinationContainerName =
hasOptionalDestinationContainerName ? options.getDestinationContainerName()
: options.getDeletedContainerName();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getContainers().restoreWithResponseAsync(finalDestinationContainerName, null,
null, options.getDeletedContainerName(), options.getDeletedContainerVersion(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response,
getBlobContainerAsyncClient(finalDestinationContainerName)));
}
} |
Good catch. Updated. | PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
options.setMaxResultsPerPage(pageSize);
return withContext(context -> this.findBlobsByTags(options, marker, timeout, context));
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
} | options.setMaxResultsPerPage(pageSize); | PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> withContext(context -> this.findBlobsByTags(
new FindBlobsOptions(options.getQuery()).setMaxResultsPerPage(pageSize), marker, timeout, context));
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
} | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
private final String accountName;
private final BlobServiceVersion serviceVersion;
private final CpkInfo customerProvidedKey;
private final EncryptionScope encryptionScope;
private final BlobContainerEncryptionScope blobContainerEncryptionScope;
private final boolean anonymousAccess;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param anonymousAccess Whether or not the client was built with anonymousAccess
*/
BlobServiceAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
CpkInfo customerProvidedKey, EncryptionScope encryptionScope,
BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) {
/* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer
when the sas token has already been applied. */
try {
URI.create(url);
} catch (IllegalArgumentException ex) {
throw logger.logExceptionAsError(ex);
}
this.azureBlobStorage = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.customerProvidedKey = customerProvidedKey;
this.encryptionScope = encryptionScope;
this.blobContainerEncryptionScope = blobContainerEncryptionScope;
this.anonymousAccess = anonymousAccess;
}
/**
* Initializes a {@link BlobContainerAsyncClient} object pointing to the specified container. This method does not
* create a container. It simply constructs the URL to the container and offers access to methods relevant to
* containers.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient
*
* @param containerName The name of the container to point to. A value of null or empty string will be interpreted
* as pointing to the root container and will be replaced by "$root".
* @return A {@link BlobContainerAsyncClient} object pointing to the specified container
*/
public BlobContainerAsyncClient getBlobContainerAsyncClient(String containerName) {
if (CoreUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
return new BlobContainerAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer
*
* @param containerName Name of the container to create
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> createBlobContainer(String containerName) {
try {
return createBlobContainerWithResponse(containerName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse
*
* @param containerName Name of the container to create
* @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this container is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
return withContext(context -> createBlobContainerWithResponse(containerName, metadata, accessType,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType, Context context) {
throwOnAnonymousAccess();
BlobContainerAsyncClient blobContainerAsyncClient = getBlobContainerAsyncClient(containerName);
return blobContainerAsyncClient.createWithResponse(metadata, accessType, context)
.map(response -> new SimpleResponse<>(response, blobContainerAsyncClient));
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlobContainer(String containerName) {
try {
return deleteBlobContainerWithResponse(containerName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName) {
try {
return withContext(context -> deleteBlobContainerWithResponse(containerName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName, Context context) {
throwOnAnonymousAccess();
return getBlobContainerAsyncClient(containerName).deleteWithResponse(null, context);
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureBlobStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers}
*
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers() {
try {
return this.listBlobContainers(new ListBlobContainersOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers
*
* @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options) {
try {
return listBlobContainersWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<BlobContainerItem> listBlobContainersWithOptionalTimeout(ListBlobContainersOptions options,
Duration timeout) {
throwOnAnonymousAccess();
BiFunction<String, Integer, Mono<PagedResponse<BlobContainerItem>>> func =
(marker, pageSize) -> {
ListBlobContainersOptions finalOptions = null;
if (pageSize != null) {
if (options == null) {
finalOptions = new ListBlobContainersOptions().setMaxResultsPerPage(pageSize);
} else {
finalOptions = new ListBlobContainersOptions()
.setMaxResultsPerPage(pageSize)
.setDetails(options.getDetails())
.setPrefix(options.getPrefix());
}
}
return listBlobContainersSegment(marker, finalOptions, timeout);
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<BlobContainerItem>> listBlobContainersSegment(String marker,
ListBlobContainersOptions options, Duration timeout) {
options = options == null ? new ListBlobContainersOptions() : options;
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().listBlobContainersSegmentSinglePageAsync(
options.getPrefix(), marker, options.getMaxResultsPerPage(),
toIncludeTypes(options.getDetails()),
null, null, Context.NONE), timeout);
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag
*
* @param query Filters the results to return only blobs whose tags match the specified expression.
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(String query) {
return this.findBlobsByTags(new FindBlobsOptions(query));
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag
*
* @param options {@link FindBlobsOptions}
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options) {
try {
return findBlobsByTags(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
FindBlobsOptions finalOptions;
if (pageSize != null) {
finalOptions = new FindBlobsOptions(options.getQuery())
.setMaxResultsPerPage(pageSize);
} else {
finalOptions = options;
}
return this.findBlobsByTags(finalOptions, marker, timeout, context);
};
return StoragePagedFlux.create(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<TaggedBlobItem>> findBlobsByTags(
FindBlobsOptions options, String marker,
Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().filterBlobsWithResponseAsync(null, null,
options.getQuery(), marker, options.getMaxResultsPerPage(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)), timeout)
.map(response -> {
List<TaggedBlobItem> value = response.getValue().getBlobs() == null
? Collections.emptyList()
: response.getValue().getBlobs().stream()
.map(ModelHelper::populateTaggedBlobItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getValue().getNextMarker(),
response.getDeserializedHeaders());
});
}
/**
* Converts {@link BlobContainerListDetails} into list of {@link ListBlobContainersIncludeType}
* that contains only options selected. If no option is selected then null is returned.
*
* @return a list of selected options converted into {@link ListBlobContainersIncludeType}, null if none
* of options has been selected.
*/
private List<ListBlobContainersIncludeType> toIncludeTypes(BlobContainerListDetails blobContainerListDetails) {
boolean hasDetails = blobContainerListDetails != null
&& (blobContainerListDetails.getRetrieveMetadata() || blobContainerListDetails.getRetrieveDeleted());
if (hasDetails) {
List<ListBlobContainersIncludeType> flags = new ArrayList<>(2);
if (blobContainerListDetails.getRetrieveDeleted()) {
flags.add(ListBlobContainersIncludeType.DELETED);
}
if (blobContainerListDetails.getRetrieveMetadata()) {
flags.add(ListBlobContainersIncludeType.METADATA);
}
return flags;
} else {
return null;
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getProperties}
*
* @return A reactive response containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceProperties> getProperties() {
try {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceProperties>> getPropertiesWithResponse() {
try {
return withContext(this::getPropertiesWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceProperties>> getPropertiesWithResponse(Context context) {
context = context == null ? Context.NONE : context;
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getPropertiesWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setProperties
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(BlobServiceProperties properties) {
try {
return setPropertiesWithResponse(properties).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties) {
try {
return withContext(context -> setPropertiesWithResponse(properties, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties, Context context) {
throwOnAnonymousAccess();
BlobServiceProperties finalProperties = null;
if (properties != null) {
finalProperties = new BlobServiceProperties();
finalProperties.setLogging(properties.getLogging());
if (finalProperties.getLogging() != null) {
StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion());
validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy");
}
finalProperties.setHourMetrics(properties.getHourMetrics());
if (finalProperties.getHourMetrics() != null) {
StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion());
validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention "
+ "Policy");
if (finalProperties.getHourMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("HourMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
finalProperties.setMinuteMetrics(properties.getMinuteMetrics());
if (finalProperties.getMinuteMetrics() != null) {
StorageImplUtils.assertNotNull("MinuteMetrics Version",
finalProperties.getMinuteMetrics().getVersion());
validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics "
+ "Retention Policy");
if (finalProperties.getMinuteMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
if (properties.getCors() != null) {
List<BlobCorsRule> corsRules = new ArrayList<>();
for (BlobCorsRule rule : properties.getCors()) {
corsRules.add(validatedCorsRule(rule));
}
finalProperties.setCors(corsRules);
}
finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion());
finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy());
validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days");
finalProperties.setStaticWebsite(properties.getStaticWebsite());
}
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().setPropertiesWithResponseAsync(finalProperties, null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Sets any null fields to "" since the service requires all Cors rules to be set if some are set.
* @param originalRule {@link BlobCorsRule}
* @return The validated {@link BlobCorsRule}
*/
private BlobCorsRule validatedCorsRule(BlobCorsRule originalRule) {
if (originalRule == null) {
return null;
}
BlobCorsRule validRule = new BlobCorsRule();
validRule.setAllowedHeaders(StorageImplUtils.emptyIfNull(originalRule.getAllowedHeaders()));
validRule.setAllowedMethods(StorageImplUtils.emptyIfNull(originalRule.getAllowedMethods()));
validRule.setAllowedOrigins(StorageImplUtils.emptyIfNull(originalRule.getAllowedOrigins()));
validRule.setExposedHeaders(StorageImplUtils.emptyIfNull(originalRule.getExposedHeaders()));
validRule.setMaxAgeInSeconds(originalRule.getMaxAgeInSeconds());
return validRule;
}
/**
* Validates a {@link BlobRetentionPolicy} according to service specs for set properties.
* @param retentionPolicy {@link BlobRetentionPolicy}
* @param policyName The name of the variable for errors.
*/
private void validateRetentionPolicy(BlobRetentionPolicy retentionPolicy, String policyName) {
if (retentionPolicy == null) {
return;
}
if (retentionPolicy.isEnabled()) {
StorageImplUtils.assertInBounds(policyName, retentionPolicy.getDays(), 1, 365);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry,
Context context) {
StorageImplUtils.assertNotNull("expiry", expiry);
if (start != null && !start.isBefore(expiry)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("`start` must be null or a datetime before `expiry`."));
}
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getUserDelegationKeyWithResponseAsync(
new KeyInfo()
.setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start))
.setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)),
null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatistics}
*
* @return A {@link Mono} containing the storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceStatistics> getStatistics() {
try {
return getStatisticsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse() {
try {
return withContext(this::getStatisticsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse(Context context) {
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getStatisticsWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo}
*
* @return A {@link Mono} containing containing the storage account info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getAccountInfoWithResponseAsync(context)
.map(rb -> {
ServicesGetAccountInfoHeaders hd = rb.getDeserializedHeaders();
return new SimpleResponse<>(rb, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind()));
});
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return generateAccountSas(accountSasSignatureValues, Context.NONE);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
throwOnAnonymousAccess();
return new AccountSasImplUtil(accountSasSignatureValues)
.generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context);
}
/**
* Checks if service client was built with credentials.
*/
private void throwOnAnonymousAccess() {
if (anonymousAccess) {
throw logger.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without "
+ "credentials"));
}
}
/**
* Restores a previously deleted container.
* If the container associated with provided <code>deletedContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer
*
* @param deletedContainerName The name of the previously deleted container.
* @param deletedContainerVersion The version of the previously deleted container.
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used
* to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> undeleteBlobContainer(
String deletedContainerName, String deletedContainerVersion) {
return this.undeleteBlobContainerWithResponse(new UndeleteBlobContainerOptions(deletedContainerName,
deletedContainerVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted container. The restored container
* will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>.
* Otherwise <code>deletedContainerName</code> is used as destination container name.
* If the container associated with provided <code>destinationContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse
*
* @param options {@link UndeleteBlobContainerOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options) {
try {
return withContext(context -> undeleteBlobContainerWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null;
String finalDestinationContainerName =
hasOptionalDestinationContainerName ? options.getDestinationContainerName()
: options.getDeletedContainerName();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getContainers().restoreWithResponseAsync(finalDestinationContainerName, null,
null, options.getDeletedContainerName(), options.getDeletedContainerVersion(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response,
getBlobContainerAsyncClient(finalDestinationContainerName)));
}
} | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
private final String accountName;
private final BlobServiceVersion serviceVersion;
private final CpkInfo customerProvidedKey;
private final EncryptionScope encryptionScope;
private final BlobContainerEncryptionScope blobContainerEncryptionScope;
private final boolean anonymousAccess;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
* @param anonymousAccess Whether or not the client was built with anonymousAccess
*/
BlobServiceAsyncClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName,
CpkInfo customerProvidedKey, EncryptionScope encryptionScope,
BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) {
/* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer
when the sas token has already been applied. */
try {
URI.create(url);
} catch (IllegalArgumentException ex) {
throw logger.logExceptionAsError(ex);
}
this.azureBlobStorage = new AzureBlobStorageImplBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.buildClient();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.customerProvidedKey = customerProvidedKey;
this.encryptionScope = encryptionScope;
this.blobContainerEncryptionScope = blobContainerEncryptionScope;
this.anonymousAccess = anonymousAccess;
}
/**
* Initializes a {@link BlobContainerAsyncClient} object pointing to the specified container. This method does not
* create a container. It simply constructs the URL to the container and offers access to methods relevant to
* containers.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient
*
* @param containerName The name of the container to point to. A value of null or empty string will be interpreted
* as pointing to the root container and will be replaced by "$root".
* @return A {@link BlobContainerAsyncClient} object pointing to the specified container
*/
public BlobContainerAsyncClient getBlobContainerAsyncClient(String containerName) {
if (CoreUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
return new BlobContainerAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(),
getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope);
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer
*
* @param containerName Name of the container to create
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> createBlobContainer(String containerName) {
try {
return createBlobContainerWithResponse(containerName, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new container within a storage account. If a container with the same name already exists, the operation
* fails. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse
*
* @param containerName Name of the container to create
* @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param accessType Specifies how the data in this container is available to the public. See the
* x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the container created.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType) {
try {
return withContext(context -> createBlobContainerWithResponse(containerName, metadata, accessType,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> createBlobContainerWithResponse(String containerName,
Map<String, String> metadata, PublicAccessType accessType, Context context) {
throwOnAnonymousAccess();
BlobContainerAsyncClient blobContainerAsyncClient = getBlobContainerAsyncClient(containerName);
return blobContainerAsyncClient.createWithResponse(metadata, accessType, context)
.map(response -> new SimpleResponse<>(response, blobContainerAsyncClient));
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlobContainer(String containerName) {
try {
return deleteBlobContainerWithResponse(containerName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For
* more information see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse
*
* @param containerName Name of the container to delete
* @return A {@link Mono} containing containing status code and HTTP headers
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName) {
try {
return withContext(context -> deleteBlobContainerWithResponse(containerName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteBlobContainerWithResponse(String containerName, Context context) {
throwOnAnonymousAccess();
return getBlobContainerAsyncClient(containerName).deleteWithResponse(null, context);
}
/**
* Gets the URL of the storage account represented by this client.
*
* @return the URL.
*/
public String getAccountUrl() {
return azureBlobStorage.getUrl();
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers}
*
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers() {
try {
return this.listBlobContainers(new ListBlobContainersOptions());
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
/**
* Returns a reactive Publisher emitting all the containers in this account lazily as needed. For more information,
* see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers
*
* @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service.
* @return A reactive response emitting the list of containers.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options) {
try {
return listBlobContainersWithOptionalTimeout(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<BlobContainerItem> listBlobContainersWithOptionalTimeout(ListBlobContainersOptions options,
Duration timeout) {
throwOnAnonymousAccess();
BiFunction<String, Integer, Mono<PagedResponse<BlobContainerItem>>> func =
(marker, pageSize) -> {
ListBlobContainersOptions finalOptions;
if (pageSize != null) {
if (options == null) {
finalOptions = new ListBlobContainersOptions().setMaxResultsPerPage(pageSize);
} else {
finalOptions = new ListBlobContainersOptions()
.setMaxResultsPerPage(pageSize)
.setDetails(options.getDetails())
.setPrefix(options.getPrefix());
}
} else {
finalOptions = options;
}
return listBlobContainersSegment(marker, finalOptions, timeout);
};
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<BlobContainerItem>> listBlobContainersSegment(String marker,
ListBlobContainersOptions options, Duration timeout) {
options = options == null ? new ListBlobContainersOptions() : options;
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().listBlobContainersSegmentSinglePageAsync(
options.getPrefix(), marker, options.getMaxResultsPerPage(),
toIncludeTypes(options.getDetails()),
null, null, Context.NONE), timeout);
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag
*
* @param query Filters the results to return only blobs whose tags match the specified expression.
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(String query) {
return this.findBlobsByTags(new FindBlobsOptions(query));
}
/**
* Returns a reactive Publisher emitting the blobs in this account whose tags match the query expression. For more
* information, including information on the query syntax, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag
*
* @param options {@link FindBlobsOptions}
* @return A reactive response emitting the list of blobs.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options) {
try {
return findBlobsByTags(options, null);
} catch (RuntimeException ex) {
return pagedFluxError(logger, ex);
}
}
PagedFlux<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
BiFunction<String, Integer, Mono<PagedResponse<TaggedBlobItem>>> func =
(marker, pageSize) -> {
FindBlobsOptions finalOptions;
if (pageSize != null) {
finalOptions = new FindBlobsOptions(options.getQuery())
.setMaxResultsPerPage(pageSize);
} else {
finalOptions = options;
}
return this.findBlobsByTags(finalOptions, marker, timeout, context);
};
return new PagedFlux<>(pageSize -> func.apply(null, pageSize), func);
}
private Mono<PagedResponse<TaggedBlobItem>> findBlobsByTags(
FindBlobsOptions options, String marker,
Duration timeout, Context context) {
throwOnAnonymousAccess();
StorageImplUtils.assertNotNull("options", options);
return StorageImplUtils.applyOptionalTimeout(
this.azureBlobStorage.getServices().filterBlobsWithResponseAsync(null, null,
options.getQuery(), marker, options.getMaxResultsPerPage(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)), timeout)
.map(response -> {
List<TaggedBlobItem> value = response.getValue().getBlobs() == null
? Collections.emptyList()
: response.getValue().getBlobs().stream()
.map(ModelHelper::populateTaggedBlobItem)
.collect(Collectors.toList());
return new PagedResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
value,
response.getValue().getNextMarker(),
response.getDeserializedHeaders());
});
}
/**
* Converts {@link BlobContainerListDetails} into list of {@link ListBlobContainersIncludeType}
* that contains only options selected. If no option is selected then null is returned.
*
* @return a list of selected options converted into {@link ListBlobContainersIncludeType}, null if none
* of options has been selected.
*/
private List<ListBlobContainersIncludeType> toIncludeTypes(BlobContainerListDetails blobContainerListDetails) {
boolean hasDetails = blobContainerListDetails != null
&& (blobContainerListDetails.getRetrieveMetadata() || blobContainerListDetails.getRetrieveDeleted());
if (hasDetails) {
List<ListBlobContainersIncludeType> flags = new ArrayList<>(2);
if (blobContainerListDetails.getRetrieveDeleted()) {
flags.add(ListBlobContainersIncludeType.DELETED);
}
if (blobContainerListDetails.getRetrieveMetadata()) {
flags.add(ListBlobContainersIncludeType.METADATA);
}
return flags;
} else {
return null;
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getProperties}
*
* @return A reactive response containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceProperties> getProperties() {
try {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the properties of a storage account’s Blob service. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceProperties>> getPropertiesWithResponse() {
try {
return withContext(this::getPropertiesWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceProperties>> getPropertiesWithResponse(Context context) {
context = context == null ? Context.NONE : context;
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getPropertiesWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setProperties
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(BlobServiceProperties properties) {
try {
return setPropertiesWithResponse(properties).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets properties for a storage account's Blob service endpoint. For more information, see the
* <a href="https:
* Note that setting the default service version has no effect when using this client because this client explicitly
* sets the version header on each request, overriding the default.
* <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs.
* If CORS policies are set, CORS parameters that are not set default to the empty string.</p>
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse
*
* @param properties Configures the service.
* @return A {@link Mono} containing the storage account properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties) {
try {
return withContext(context -> setPropertiesWithResponse(properties, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setPropertiesWithResponse(BlobServiceProperties properties, Context context) {
throwOnAnonymousAccess();
BlobServiceProperties finalProperties = null;
if (properties != null) {
finalProperties = new BlobServiceProperties();
finalProperties.setLogging(properties.getLogging());
if (finalProperties.getLogging() != null) {
StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion());
validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy");
}
finalProperties.setHourMetrics(properties.getHourMetrics());
if (finalProperties.getHourMetrics() != null) {
StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion());
validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention "
+ "Policy");
if (finalProperties.getHourMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("HourMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
finalProperties.setMinuteMetrics(properties.getMinuteMetrics());
if (finalProperties.getMinuteMetrics() != null) {
StorageImplUtils.assertNotNull("MinuteMetrics Version",
finalProperties.getMinuteMetrics().getVersion());
validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics "
+ "Retention Policy");
if (finalProperties.getMinuteMetrics().isEnabled()) {
StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis",
finalProperties.getHourMetrics().isIncludeApis());
}
}
if (properties.getCors() != null) {
List<BlobCorsRule> corsRules = new ArrayList<>();
for (BlobCorsRule rule : properties.getCors()) {
corsRules.add(validatedCorsRule(rule));
}
finalProperties.setCors(corsRules);
}
finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion());
finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy());
validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days");
finalProperties.setStaticWebsite(properties.getStaticWebsite());
}
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().setPropertiesWithResponseAsync(finalProperties, null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Sets any null fields to "" since the service requires all Cors rules to be set if some are set.
* @param originalRule {@link BlobCorsRule}
* @return The validated {@link BlobCorsRule}
*/
private BlobCorsRule validatedCorsRule(BlobCorsRule originalRule) {
if (originalRule == null) {
return null;
}
BlobCorsRule validRule = new BlobCorsRule();
validRule.setAllowedHeaders(StorageImplUtils.emptyIfNull(originalRule.getAllowedHeaders()));
validRule.setAllowedMethods(StorageImplUtils.emptyIfNull(originalRule.getAllowedMethods()));
validRule.setAllowedOrigins(StorageImplUtils.emptyIfNull(originalRule.getAllowedOrigins()));
validRule.setExposedHeaders(StorageImplUtils.emptyIfNull(originalRule.getExposedHeaders()));
validRule.setMaxAgeInSeconds(originalRule.getMaxAgeInSeconds());
return validRule;
}
/**
* Validates a {@link BlobRetentionPolicy} according to service specs for set properties.
* @param retentionPolicy {@link BlobRetentionPolicy}
* @param policyName The name of the variable for errors.
*/
private void validateRetentionPolicy(BlobRetentionPolicy retentionPolicy, String policyName) {
if (retentionPolicy == null) {
return;
}
if (retentionPolicy.isEnabled()) {
StorageImplUtils.assertInBounds(policyName, retentionPolicy.getDays(), 1, 365);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing the user delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when
* using {@link TokenCredential} in this object's {@link HttpPipeline}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse
*
* @param start Start time for the key's validity. Null indicates immediate start.
* @param expiry Expiration of the key's validity.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* delegation key.
* @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
* @throws NullPointerException If {@code expiry} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
OffsetDateTime expiry) {
try {
return withContext(context -> getUserDelegationKeyWithResponse(start, expiry, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry,
Context context) {
StorageImplUtils.assertNotNull("expiry", expiry);
if (start != null && !start.isBefore(expiry)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("`start` must be null or a datetime before `expiry`."));
}
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getUserDelegationKeyWithResponseAsync(
new KeyInfo()
.setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start))
.setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)),
null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatistics}
*
* @return A {@link Mono} containing the storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobServiceStatistics> getStatistics() {
try {
return getStatisticsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the secondary location
* endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see
* the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* storage account statistics.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse() {
try {
return withContext(this::getStatisticsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobServiceStatistics>> getStatisticsWithResponse(Context context) {
throwOnAnonymousAccess();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getServices().getStatisticsWithResponseAsync(null, null,
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(rb -> new SimpleResponse<>(rb, rb.getValue()));
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo}
*
* @return A {@link Mono} containing containing the storage account info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account. For more information, please see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* info.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
throwOnAnonymousAccess();
return this.azureBlobStorage.getServices().getAccountInfoWithResponseAsync(context)
.map(rb -> {
ServicesGetAccountInfoHeaders hd = rb.getDeserializedHeaders();
return new SimpleResponse<>(rb, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind()));
});
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
return generateAccountSas(accountSasSignatureValues, Context.NONE);
}
/**
* Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
* <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential}
* <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p>
*
* <p>The snippet below generates a SAS that lasts for two days and gives the user read and list access to blob
* containers and file shares.</p>
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas
*
* @param accountSasSignatureValues {@link AccountSasSignatureValues}
* @param context Additional context that is passed through the code when generating a SAS.
*
* @return A {@code String} representing the SAS query parameters.
*/
public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) {
throwOnAnonymousAccess();
return new AccountSasImplUtil(accountSasSignatureValues)
.generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context);
}
/**
* Checks if service client was built with credentials.
*/
private void throwOnAnonymousAccess() {
if (anonymousAccess) {
throw logger.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without "
+ "credentials"));
}
}
/**
* Restores a previously deleted container.
* If the container associated with provided <code>deletedContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer
*
* @param deletedContainerName The name of the previously deleted container.
* @param deletedContainerVersion The version of the previously deleted container.
* @return A {@link Mono} containing a {@link BlobContainerAsyncClient} used
* to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobContainerAsyncClient> undeleteBlobContainer(
String deletedContainerName, String deletedContainerVersion) {
return this.undeleteBlobContainerWithResponse(new UndeleteBlobContainerOptions(deletedContainerName,
deletedContainerVersion)
).flatMap(FluxUtil::toMono);
}
/**
* Restores a previously deleted container. The restored container
* will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>.
* Otherwise <code>deletedContainerName</code> is used as destination container name.
* If the container associated with provided <code>destinationContainerName</code>
* already exists, this call will result in a 409 (conflict).
* This API is only functional if Container Soft Delete is enabled
* for the storage account associated with the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse
*
* @param options {@link UndeleteBlobContainerOptions}.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* BlobContainerAsyncClient} used to interact with the restored container.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options) {
try {
return withContext(context -> undeleteBlobContainerWithResponse(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobContainerAsyncClient>> undeleteBlobContainerWithResponse(
UndeleteBlobContainerOptions options, Context context) {
StorageImplUtils.assertNotNull("options", options);
boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null;
String finalDestinationContainerName =
hasOptionalDestinationContainerName ? options.getDestinationContainerName()
: options.getDeletedContainerName();
context = context == null ? Context.NONE : context;
return this.azureBlobStorage.getContainers().restoreWithResponseAsync(finalDestinationContainerName, null,
null, options.getDeletedContainerName(), options.getDeletedContainerVersion(),
context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE))
.map(response -> new SimpleResponse<>(response,
getBlobContainerAsyncClient(finalDestinationContainerName)));
}
} |
I would go with `debug` as it won't affect runtime of an application, aside not having a warm startup. | private static void attemptToWarmupHttpClient(ReactorNettyClient reactorNettyClient) {
if (HTTP_CLIENT_WARMUP == null) {
return;
}
try {
((Mono<?>) HTTP_CLIENT_WARMUP.invoke(reactorNettyClient.httpClient)).block();
} catch (ClassCastException | WrongMethodTypeException throwable) {
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
} | private static void attemptToWarmupHttpClient(ReactorNettyClient reactorNettyClient) {
if (HTTP_CLIENT_WARMUP == null) {
return;
}
try {
((Mono<?>) HTTP_CLIENT_WARMUP.invoke(reactorNettyClient.httpClient)).block();
} catch (ClassCastException | WrongMethodTypeException throwable) {
logger.debug("Invoking HttpClient.warmup failed.", throwable);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
} | class ReactorNettyClient implements HttpClient {
private static final String REACTOR_NETTY_REQUEST_RECORD_KEY = "reactorNettyRequestRecordKey";
private static final Logger logger = LoggerFactory.getLogger(ReactorNettyClient.class.getSimpleName());
private static final MethodHandle HTTP_CLIENT_WARMUP;
static {
MethodHandle httpClientWarmup = null;
try {
httpClientWarmup = MethodHandles.publicLookup()
.findVirtual(reactor.netty.http.client.HttpClient.class, "warmup", MethodType.methodType(Mono.class));
} catch (Throwable throwable) {
}
HTTP_CLIENT_WARMUP = httpClientWarmup;
}
private HttpClientConfig httpClientConfig;
private reactor.netty.http.client.HttpClient httpClient;
private ConnectionProvider connectionProvider;
private ReactorNettyClient() {}
/**
* Creates ReactorNettyClient with un-pooled connection.
*/
public static ReactorNettyClient create(HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.newConnection()
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/**
* Creates ReactorNettyClient with {@link ConnectionProvider}.
*/
public static ReactorNettyClient createWithConnectionProvider(ConnectionProvider connectionProvider, HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.connectionProvider = connectionProvider;
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.create(connectionProvider)
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/*
* This enables fast warm up of HttpClient
*/
private void configureChannelPipelineHandlers() {
Configs configs = this.httpClientConfig.getConfigs();
if (this.httpClientConfig.getProxy() != null) {
this.httpClient = this.httpClient.proxy(typeSpec -> typeSpec.type(ProxyProvider.Proxy.HTTP)
.address(this.httpClientConfig.getProxy().getAddress()));
}
if (LoggerFactory.getLogger(REACTOR_NETWORK_LOG_CATEGORY).isTraceEnabled()) {
this.httpClient = this.httpClient.wiretap(REACTOR_NETWORK_LOG_CATEGORY, LogLevel.INFO);
}
this.httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(configs.getSslContext()))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) configs.getConnectionAcquireTimeout().toMillis())
.httpResponseDecoder(httpResponseDecoderSpec ->
httpResponseDecoderSpec.maxInitialLineLength(configs.getMaxHttpInitialLineLength())
.maxHeaderSize(configs.getMaxHttpHeaderSize())
.maxChunkSize(configs.getMaxHttpChunkSize())
.validateHeaders(true));
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
}
@Override
public Mono<HttpResponse> send(final HttpRequest request, Duration responseTimeout) {
Objects.requireNonNull(request.httpMethod());
Objects.requireNonNull(request.uri());
Objects.requireNonNull(this.httpClientConfig);
if(request.reactorNettyRequestRecord() == null) {
ReactorNettyRequestRecord reactorNettyRequestRecord = new ReactorNettyRequestRecord();
reactorNettyRequestRecord.setTimeCreated(Instant.now());
request.withReactorNettyRequestRecord(reactorNettyRequestRecord);
}
final AtomicReference<ReactorNettyHttpResponse> responseReference = new AtomicReference<>();
return this.httpClient
.keepAlive(this.httpClientConfig.isConnectionKeepAlive())
.port(request.port())
.responseTimeout(responseTimeout)
.request(HttpMethod.valueOf(request.httpMethod().toString()))
.uri(request.uri().toString())
.send(bodySendDelegate(request))
.responseConnection((reactorNettyResponse, reactorNettyConnection) -> {
HttpResponse httpResponse = new ReactorNettyHttpResponse(reactorNettyResponse,
reactorNettyConnection).withRequest(request);
responseReference.set((ReactorNettyHttpResponse) httpResponse);
return Mono.just(httpResponse);
})
.contextWrite(Context.of(REACTOR_NETTY_REQUEST_RECORD_KEY, request.reactorNettyRequestRecord()))
.doOnCancel(() -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.CANCELLED);
}
})
.onErrorMap(throwable -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.ERROR);
}
return throwable;
})
.single();
}
/**
* Delegate to send the request content.
*
* @param restRequest the Rest request contains the body to be sent
* @return a delegate upon invocation sets the request body in reactor-netty outbound object
*/
private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate(final HttpRequest restRequest) {
return (reactorNettyRequest, reactorNettyOutbound) -> {
for (HttpHeader header : restRequest.headers()) {
reactorNettyRequest.header(header.name(), header.value());
}
if (restRequest.body() != null) {
return reactorNettyOutbound.sendByteArray(restRequest.body());
} else {
return reactorNettyOutbound;
}
};
}
@Override
public void shutdown() {
if (this.connectionProvider != null) {
this.connectionProvider.dispose();
}
}
private static ConnectionObserver getConnectionObserver() {
return (conn, state) -> {
Instant time = Instant.now();
if (state.equals(HttpClientState.CONNECTED) || state.equals(HttpClientState.ACQUIRED)) {
if (conn instanceof ConnectionObserver) {
ConnectionObserver observer = (ConnectionObserver) conn;
ReactorNettyRequestRecord requestRecord =
observer.currentContext().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConnected(time);
}
} else if (state.equals(HttpClientState.CONFIGURED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConfigured(time);
}
} else if (state.equals(HttpClientState.REQUEST_SENT)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeSent(time);
}
} else if (state.equals(HttpClientState.RESPONSE_RECEIVED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeReceived(time);
}
}
};
}
private static class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation or error is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation or error happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseOnNotSubscribedResponse(ReactorNettyResponseState reactorNettyResponseState) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, reactorNettyResponseState)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
}
private enum ReactorNettyResponseState {
NOT_SUBSCRIBED,
SUBSCRIBED,
CANCELLED,
ERROR;
}
} | class ReactorNettyClient implements HttpClient {
private static final String REACTOR_NETTY_REQUEST_RECORD_KEY = "reactorNettyRequestRecordKey";
private static final Logger logger = LoggerFactory.getLogger(ReactorNettyClient.class.getSimpleName());
private static final MethodHandle HTTP_CLIENT_WARMUP;
static {
MethodHandle httpClientWarmup = null;
try {
httpClientWarmup = MethodHandles.publicLookup()
.findVirtual(reactor.netty.http.client.HttpClient.class, "warmup", MethodType.methodType(Mono.class));
} catch (IllegalAccessException | NoSuchMethodException ex) {
}
HTTP_CLIENT_WARMUP = httpClientWarmup;
}
private HttpClientConfig httpClientConfig;
private reactor.netty.http.client.HttpClient httpClient;
private ConnectionProvider connectionProvider;
private ReactorNettyClient() {}
/**
* Creates ReactorNettyClient with un-pooled connection.
*/
public static ReactorNettyClient create(HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.newConnection()
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/**
* Creates ReactorNettyClient with {@link ConnectionProvider}.
*/
public static ReactorNettyClient createWithConnectionProvider(ConnectionProvider connectionProvider, HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.connectionProvider = connectionProvider;
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.create(connectionProvider)
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/*
* This enables fast warm up of HttpClient
*/
private void configureChannelPipelineHandlers() {
Configs configs = this.httpClientConfig.getConfigs();
if (this.httpClientConfig.getProxy() != null) {
this.httpClient = this.httpClient.proxy(typeSpec -> typeSpec.type(ProxyProvider.Proxy.HTTP)
.address(this.httpClientConfig.getProxy().getAddress()));
}
if (LoggerFactory.getLogger(REACTOR_NETWORK_LOG_CATEGORY).isTraceEnabled()) {
this.httpClient = this.httpClient.wiretap(REACTOR_NETWORK_LOG_CATEGORY, LogLevel.INFO);
}
this.httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(configs.getSslContext()))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) configs.getConnectionAcquireTimeout().toMillis())
.httpResponseDecoder(httpResponseDecoderSpec ->
httpResponseDecoderSpec.maxInitialLineLength(configs.getMaxHttpInitialLineLength())
.maxHeaderSize(configs.getMaxHttpHeaderSize())
.maxChunkSize(configs.getMaxHttpChunkSize())
.validateHeaders(true));
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
}
@Override
public Mono<HttpResponse> send(final HttpRequest request, Duration responseTimeout) {
Objects.requireNonNull(request.httpMethod());
Objects.requireNonNull(request.uri());
Objects.requireNonNull(this.httpClientConfig);
if(request.reactorNettyRequestRecord() == null) {
ReactorNettyRequestRecord reactorNettyRequestRecord = new ReactorNettyRequestRecord();
reactorNettyRequestRecord.setTimeCreated(Instant.now());
request.withReactorNettyRequestRecord(reactorNettyRequestRecord);
}
final AtomicReference<ReactorNettyHttpResponse> responseReference = new AtomicReference<>();
return this.httpClient
.keepAlive(this.httpClientConfig.isConnectionKeepAlive())
.port(request.port())
.responseTimeout(responseTimeout)
.request(HttpMethod.valueOf(request.httpMethod().toString()))
.uri(request.uri().toString())
.send(bodySendDelegate(request))
.responseConnection((reactorNettyResponse, reactorNettyConnection) -> {
HttpResponse httpResponse = new ReactorNettyHttpResponse(reactorNettyResponse,
reactorNettyConnection).withRequest(request);
responseReference.set((ReactorNettyHttpResponse) httpResponse);
return Mono.just(httpResponse);
})
.contextWrite(Context.of(REACTOR_NETTY_REQUEST_RECORD_KEY, request.reactorNettyRequestRecord()))
.doOnCancel(() -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.CANCELLED);
}
})
.onErrorMap(throwable -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.ERROR);
}
return throwable;
})
.single();
}
/**
* Delegate to send the request content.
*
* @param restRequest the Rest request contains the body to be sent
* @return a delegate upon invocation sets the request body in reactor-netty outbound object
*/
private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate(final HttpRequest restRequest) {
return (reactorNettyRequest, reactorNettyOutbound) -> {
for (HttpHeader header : restRequest.headers()) {
reactorNettyRequest.header(header.name(), header.value());
}
if (restRequest.body() != null) {
return reactorNettyOutbound.sendByteArray(restRequest.body());
} else {
return reactorNettyOutbound;
}
};
}
@Override
public void shutdown() {
if (this.connectionProvider != null) {
this.connectionProvider.dispose();
}
}
private static ConnectionObserver getConnectionObserver() {
return (conn, state) -> {
Instant time = Instant.now();
if (state.equals(HttpClientState.CONNECTED) || state.equals(HttpClientState.ACQUIRED)) {
if (conn instanceof ConnectionObserver) {
ConnectionObserver observer = (ConnectionObserver) conn;
ReactorNettyRequestRecord requestRecord =
observer.currentContext().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConnected(time);
}
} else if (state.equals(HttpClientState.CONFIGURED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConfigured(time);
}
} else if (state.equals(HttpClientState.REQUEST_SENT)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeSent(time);
}
} else if (state.equals(HttpClientState.RESPONSE_RECEIVED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeReceived(time);
}
}
};
}
private static class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation or error is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation or error happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseOnNotSubscribedResponse(ReactorNettyResponseState reactorNettyResponseState) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, reactorNettyResponseState)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
}
private enum ReactorNettyResponseState {
NOT_SUBSCRIBED,
SUBSCRIBED,
CANCELLED,
ERROR;
}
} | |
Makes sense, thanks @alzimmermsft | private static void attemptToWarmupHttpClient(ReactorNettyClient reactorNettyClient) {
if (HTTP_CLIENT_WARMUP == null) {
return;
}
try {
((Mono<?>) HTTP_CLIENT_WARMUP.invoke(reactorNettyClient.httpClient)).block();
} catch (ClassCastException | WrongMethodTypeException throwable) {
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
} | private static void attemptToWarmupHttpClient(ReactorNettyClient reactorNettyClient) {
if (HTTP_CLIENT_WARMUP == null) {
return;
}
try {
((Mono<?>) HTTP_CLIENT_WARMUP.invoke(reactorNettyClient.httpClient)).block();
} catch (ClassCastException | WrongMethodTypeException throwable) {
logger.debug("Invoking HttpClient.warmup failed.", throwable);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
} | class ReactorNettyClient implements HttpClient {
private static final String REACTOR_NETTY_REQUEST_RECORD_KEY = "reactorNettyRequestRecordKey";
private static final Logger logger = LoggerFactory.getLogger(ReactorNettyClient.class.getSimpleName());
private static final MethodHandle HTTP_CLIENT_WARMUP;
static {
MethodHandle httpClientWarmup = null;
try {
httpClientWarmup = MethodHandles.publicLookup()
.findVirtual(reactor.netty.http.client.HttpClient.class, "warmup", MethodType.methodType(Mono.class));
} catch (Throwable throwable) {
}
HTTP_CLIENT_WARMUP = httpClientWarmup;
}
private HttpClientConfig httpClientConfig;
private reactor.netty.http.client.HttpClient httpClient;
private ConnectionProvider connectionProvider;
private ReactorNettyClient() {}
/**
* Creates ReactorNettyClient with un-pooled connection.
*/
public static ReactorNettyClient create(HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.newConnection()
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/**
* Creates ReactorNettyClient with {@link ConnectionProvider}.
*/
public static ReactorNettyClient createWithConnectionProvider(ConnectionProvider connectionProvider, HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.connectionProvider = connectionProvider;
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.create(connectionProvider)
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/*
* This enables fast warm up of HttpClient
*/
private void configureChannelPipelineHandlers() {
Configs configs = this.httpClientConfig.getConfigs();
if (this.httpClientConfig.getProxy() != null) {
this.httpClient = this.httpClient.proxy(typeSpec -> typeSpec.type(ProxyProvider.Proxy.HTTP)
.address(this.httpClientConfig.getProxy().getAddress()));
}
if (LoggerFactory.getLogger(REACTOR_NETWORK_LOG_CATEGORY).isTraceEnabled()) {
this.httpClient = this.httpClient.wiretap(REACTOR_NETWORK_LOG_CATEGORY, LogLevel.INFO);
}
this.httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(configs.getSslContext()))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) configs.getConnectionAcquireTimeout().toMillis())
.httpResponseDecoder(httpResponseDecoderSpec ->
httpResponseDecoderSpec.maxInitialLineLength(configs.getMaxHttpInitialLineLength())
.maxHeaderSize(configs.getMaxHttpHeaderSize())
.maxChunkSize(configs.getMaxHttpChunkSize())
.validateHeaders(true));
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
}
@Override
public Mono<HttpResponse> send(final HttpRequest request, Duration responseTimeout) {
Objects.requireNonNull(request.httpMethod());
Objects.requireNonNull(request.uri());
Objects.requireNonNull(this.httpClientConfig);
if(request.reactorNettyRequestRecord() == null) {
ReactorNettyRequestRecord reactorNettyRequestRecord = new ReactorNettyRequestRecord();
reactorNettyRequestRecord.setTimeCreated(Instant.now());
request.withReactorNettyRequestRecord(reactorNettyRequestRecord);
}
final AtomicReference<ReactorNettyHttpResponse> responseReference = new AtomicReference<>();
return this.httpClient
.keepAlive(this.httpClientConfig.isConnectionKeepAlive())
.port(request.port())
.responseTimeout(responseTimeout)
.request(HttpMethod.valueOf(request.httpMethod().toString()))
.uri(request.uri().toString())
.send(bodySendDelegate(request))
.responseConnection((reactorNettyResponse, reactorNettyConnection) -> {
HttpResponse httpResponse = new ReactorNettyHttpResponse(reactorNettyResponse,
reactorNettyConnection).withRequest(request);
responseReference.set((ReactorNettyHttpResponse) httpResponse);
return Mono.just(httpResponse);
})
.contextWrite(Context.of(REACTOR_NETTY_REQUEST_RECORD_KEY, request.reactorNettyRequestRecord()))
.doOnCancel(() -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.CANCELLED);
}
})
.onErrorMap(throwable -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.ERROR);
}
return throwable;
})
.single();
}
/**
* Delegate to send the request content.
*
* @param restRequest the Rest request contains the body to be sent
* @return a delegate upon invocation sets the request body in reactor-netty outbound object
*/
private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate(final HttpRequest restRequest) {
return (reactorNettyRequest, reactorNettyOutbound) -> {
for (HttpHeader header : restRequest.headers()) {
reactorNettyRequest.header(header.name(), header.value());
}
if (restRequest.body() != null) {
return reactorNettyOutbound.sendByteArray(restRequest.body());
} else {
return reactorNettyOutbound;
}
};
}
@Override
public void shutdown() {
if (this.connectionProvider != null) {
this.connectionProvider.dispose();
}
}
private static ConnectionObserver getConnectionObserver() {
return (conn, state) -> {
Instant time = Instant.now();
if (state.equals(HttpClientState.CONNECTED) || state.equals(HttpClientState.ACQUIRED)) {
if (conn instanceof ConnectionObserver) {
ConnectionObserver observer = (ConnectionObserver) conn;
ReactorNettyRequestRecord requestRecord =
observer.currentContext().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConnected(time);
}
} else if (state.equals(HttpClientState.CONFIGURED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConfigured(time);
}
} else if (state.equals(HttpClientState.REQUEST_SENT)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeSent(time);
}
} else if (state.equals(HttpClientState.RESPONSE_RECEIVED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeReceived(time);
}
}
};
}
private static class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation or error is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation or error happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseOnNotSubscribedResponse(ReactorNettyResponseState reactorNettyResponseState) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, reactorNettyResponseState)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
}
private enum ReactorNettyResponseState {
NOT_SUBSCRIBED,
SUBSCRIBED,
CANCELLED,
ERROR;
}
} | class ReactorNettyClient implements HttpClient {
private static final String REACTOR_NETTY_REQUEST_RECORD_KEY = "reactorNettyRequestRecordKey";
private static final Logger logger = LoggerFactory.getLogger(ReactorNettyClient.class.getSimpleName());
private static final MethodHandle HTTP_CLIENT_WARMUP;
static {
MethodHandle httpClientWarmup = null;
try {
httpClientWarmup = MethodHandles.publicLookup()
.findVirtual(reactor.netty.http.client.HttpClient.class, "warmup", MethodType.methodType(Mono.class));
} catch (IllegalAccessException | NoSuchMethodException ex) {
}
HTTP_CLIENT_WARMUP = httpClientWarmup;
}
private HttpClientConfig httpClientConfig;
private reactor.netty.http.client.HttpClient httpClient;
private ConnectionProvider connectionProvider;
private ReactorNettyClient() {}
/**
* Creates ReactorNettyClient with un-pooled connection.
*/
public static ReactorNettyClient create(HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.newConnection()
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/**
* Creates ReactorNettyClient with {@link ConnectionProvider}.
*/
public static ReactorNettyClient createWithConnectionProvider(ConnectionProvider connectionProvider, HttpClientConfig httpClientConfig) {
ReactorNettyClient reactorNettyClient = new ReactorNettyClient();
reactorNettyClient.connectionProvider = connectionProvider;
reactorNettyClient.httpClientConfig = httpClientConfig;
reactorNettyClient.httpClient = reactor.netty.http.client.HttpClient
.create(connectionProvider)
.observe(getConnectionObserver())
.resolver(DefaultAddressResolverGroup.INSTANCE);
reactorNettyClient.configureChannelPipelineHandlers();
attemptToWarmupHttpClient(reactorNettyClient);
return reactorNettyClient;
}
/*
* This enables fast warm up of HttpClient
*/
private void configureChannelPipelineHandlers() {
Configs configs = this.httpClientConfig.getConfigs();
if (this.httpClientConfig.getProxy() != null) {
this.httpClient = this.httpClient.proxy(typeSpec -> typeSpec.type(ProxyProvider.Proxy.HTTP)
.address(this.httpClientConfig.getProxy().getAddress()));
}
if (LoggerFactory.getLogger(REACTOR_NETWORK_LOG_CATEGORY).isTraceEnabled()) {
this.httpClient = this.httpClient.wiretap(REACTOR_NETWORK_LOG_CATEGORY, LogLevel.INFO);
}
this.httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(configs.getSslContext()))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) configs.getConnectionAcquireTimeout().toMillis())
.httpResponseDecoder(httpResponseDecoderSpec ->
httpResponseDecoderSpec.maxInitialLineLength(configs.getMaxHttpInitialLineLength())
.maxHeaderSize(configs.getMaxHttpHeaderSize())
.maxChunkSize(configs.getMaxHttpChunkSize())
.validateHeaders(true));
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return send(request, Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()));
}
@Override
public Mono<HttpResponse> send(final HttpRequest request, Duration responseTimeout) {
Objects.requireNonNull(request.httpMethod());
Objects.requireNonNull(request.uri());
Objects.requireNonNull(this.httpClientConfig);
if(request.reactorNettyRequestRecord() == null) {
ReactorNettyRequestRecord reactorNettyRequestRecord = new ReactorNettyRequestRecord();
reactorNettyRequestRecord.setTimeCreated(Instant.now());
request.withReactorNettyRequestRecord(reactorNettyRequestRecord);
}
final AtomicReference<ReactorNettyHttpResponse> responseReference = new AtomicReference<>();
return this.httpClient
.keepAlive(this.httpClientConfig.isConnectionKeepAlive())
.port(request.port())
.responseTimeout(responseTimeout)
.request(HttpMethod.valueOf(request.httpMethod().toString()))
.uri(request.uri().toString())
.send(bodySendDelegate(request))
.responseConnection((reactorNettyResponse, reactorNettyConnection) -> {
HttpResponse httpResponse = new ReactorNettyHttpResponse(reactorNettyResponse,
reactorNettyConnection).withRequest(request);
responseReference.set((ReactorNettyHttpResponse) httpResponse);
return Mono.just(httpResponse);
})
.contextWrite(Context.of(REACTOR_NETTY_REQUEST_RECORD_KEY, request.reactorNettyRequestRecord()))
.doOnCancel(() -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.CANCELLED);
}
})
.onErrorMap(throwable -> {
ReactorNettyHttpResponse reactorNettyHttpResponse = responseReference.get();
if (reactorNettyHttpResponse != null) {
reactorNettyHttpResponse.releaseOnNotSubscribedResponse(ReactorNettyResponseState.ERROR);
}
return throwable;
})
.single();
}
/**
* Delegate to send the request content.
*
* @param restRequest the Rest request contains the body to be sent
* @return a delegate upon invocation sets the request body in reactor-netty outbound object
*/
private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate(final HttpRequest restRequest) {
return (reactorNettyRequest, reactorNettyOutbound) -> {
for (HttpHeader header : restRequest.headers()) {
reactorNettyRequest.header(header.name(), header.value());
}
if (restRequest.body() != null) {
return reactorNettyOutbound.sendByteArray(restRequest.body());
} else {
return reactorNettyOutbound;
}
};
}
@Override
public void shutdown() {
if (this.connectionProvider != null) {
this.connectionProvider.dispose();
}
}
private static ConnectionObserver getConnectionObserver() {
return (conn, state) -> {
Instant time = Instant.now();
if (state.equals(HttpClientState.CONNECTED) || state.equals(HttpClientState.ACQUIRED)) {
if (conn instanceof ConnectionObserver) {
ConnectionObserver observer = (ConnectionObserver) conn;
ReactorNettyRequestRecord requestRecord =
observer.currentContext().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConnected(time);
}
} else if (state.equals(HttpClientState.CONFIGURED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeConfigured(time);
}
} else if (state.equals(HttpClientState.REQUEST_SENT)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeSent(time);
}
} else if (state.equals(HttpClientState.RESPONSE_RECEIVED)) {
if (conn instanceof HttpClientRequest) {
HttpClientRequest httpClientRequest = (HttpClientRequest) conn;
ReactorNettyRequestRecord requestRecord =
httpClientRequest.currentContextView().getOrDefault(REACTOR_NETTY_REQUEST_RECORD_KEY, null);
if (requestRecord == null) {
throw new IllegalStateException("ReactorNettyRequestRecord not found in context");
}
requestRecord.setTimeReceived(time);
}
}
};
}
private static class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation or error is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation or error happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseOnNotSubscribedResponse(ReactorNettyResponseState reactorNettyResponseState) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, reactorNettyResponseState)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
}
private enum ReactorNettyResponseState {
NOT_SUBSCRIBED,
SUBSCRIBED,
CANCELLED,
ERROR;
}
} | |
Let's return a `Mono.error` #Resolved | Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
} | throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")); | Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
} |
Should still be able to use the `FluxUtil` method to remove the response, correct? #Resolved | public Mono<Void> deleteRegistryArtifact(String digest) {
return this.deleteRegistryArtifactWithResponse(digest)
.flatMap((Response<Void> res) -> Mono.empty());
} | .flatMap((Response<Void> res) -> Mono.empty()); | public Mono<Void> deleteRegistryArtifact(String digest) {
return this.deleteRegistryArtifactWithResponse(digest).flatMap(FluxUtil::toMono);
} | class ContainerRepositoryAsyncClient {
private final ContainerRegistryRepositoriesImpl serviceClient;
private final ContainerRegistriesImpl registriesImplClient;
private final String repositoryName;
private final String endpoint;
private final String apiVersion;
private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class);
ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String apiVersion) {
if (repositoryName == null) {
throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null"));
}
ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder()
.pipeline(httpPipeline)
.serializerAdapter(serializerAdapter)
.url(endpoint).buildClient();
this.endpoint = endpoint;
this.repositoryName = repositoryName;
this.registriesImplClient = registryImpl.getContainerRegistries();
this.serviceClient = registryImpl.getContainerRegistryRepositories();
this.apiVersion = apiVersion;
}
/**
* Get endpoint associated with the class.
* @return String the endpoint associated with this client.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* Get the registry associated with the client.
* @return Return the registry name.
*/
public String getRegistry() {
return this.endpoint;
}
/**
* Get repository associated with the class.
* @return Return the repository name.
* */
public String getRepository() {
return this.repositoryName;
}
/**
* Delete repository.
*
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() {
return withContext(context -> deleteWithResponse(context));
}
/**
* Delete repository.
*
* @param context Context associated with the operation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) {
try {
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context)
.map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult))
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete repository.
*
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> delete() {
return this.deleteWithResponse().map(Response::getValue);
}
/**
* Delete registry artifact.
*
* @param digest Digest name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) {
return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context));
}
Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) {
try {
if (digest == null) {
return monoError(logger, new NullPointerException("'digest' cannot be null"));
}
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete registry artifact.
*
* @param digest digest to delete.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Delete tag.
*
* @param tag tag name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTagWithResponse(String tag) {
return withContext(context -> this.deleteTagWithResponse(tag, context));
}
Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) {
try {
if (tag == null) {
return monoError(logger, new NullPointerException("'digest' cannot be null"));
}
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete tag.
*
* @param tag Tag name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTag(String tag) {
return this.deleteTagWithResponse(tag)
.flatMap((Response<Void> res) -> Mono.empty());
}
/**
* Get repository properties.
*
* @return repository properties.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() {
return withContext(context -> this.getPropertiesWithResponse(context));
}
Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) {
try {
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context)
.map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get repository properties.
*
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return repository properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RepositoryProperties> getProperties() {
return this.getPropertiesWithResponse().map(Response::getValue);
}
/**
* Get registry artifact properties.
*
* @param tagOrDigest tag or digest associated with the blob.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return registry artifact properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) {
return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context));
}
Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) {
try {
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
Mono<String> getTagMono = Mono.defer(
() -> tagOrDigest.contains(":")
? Mono.just(tagOrDigest)
: this.getTagProperties(tagOrDigest).map(a -> a.getDigest()));
return getTagMono
.flatMap(tag -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, tag))
.map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get registry artifact properties.
*
* @param tagOrDigest tag or digest associated with the blob.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return registry artifact properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) {
return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).map(Response::getValue);
}
/**
* List registry artifacts based of a repository.
*
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return manifest attributes.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() {
return listRegistryArtifacts(null);
}
/**
* List manifests of a repository.
*
* @param options the options associated with the list registy operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return manifest attributes.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) {
return new PagedFlux<>(
(pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)),
(token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) {
try {
if (pageSize != null && pageSize < 0) {
return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative."));
}
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
String orderBy = null;
if (options != null && options.getRegistryArtifactOrderBy() != null) {
orderBy = options.getRegistryArtifactOrderBy().toString();
}
return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context)
.map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) {
try {
return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context)
.map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Get tag properties
*
* @param tag Tag name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return tag attributes by tag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) {
return withContext(context -> getTagPropertiesWithResponse(tag, context));
}
Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) {
try {
if (tag == null) {
return monoError(logger, new NullPointerException("'tag' cannot be null."));
}
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context)
.map(res -> Utils.mapResponse(res, Utils::mapTagProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get tag attributes.
*
* @param tag Tag name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return tag attributes by tag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TagProperties> getTagProperties(String tag) {
return this.getTagPropertiesWithResponse(tag).map(Response::getValue);
}
/**
* List tags of a repository.
*
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return list of tag details.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TagProperties> listTags() {
return listTags(null);
}
/**
* List tags of a repository.
*
* @param options tagOptions to be used for the given operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return list of tag details.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TagProperties> listTags(ListTagsOptions options) {
return new PagedFlux<>(
(pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)),
(token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) {
try {
if (pageSize != null && pageSize < 0) {
return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative."));
}
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
String orderBy = null;
if (options != null && options.getTagOrderBy() != null) {
orderBy = options.getTagOrderBy().toString();
}
return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context)
.map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues)
{
Objects.requireNonNull(baseValues);
return baseValues.stream().map(value -> new TagProperties(
value.getName(),
repositoryName,
value.getDigest(),
value.getWriteableProperties(),
value.getCreatedOn(),
value.getLastUpdatedOn()
)).collect(Collectors.toList());
}
Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) {
try {
return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context)
.map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Update the attribute identified by `name` where `reference` is the name of the repository.
*
* @param value Repository attribute value.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) {
return withContext(context -> this.setPropertiesWithResponse(value, context));
}
Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) {
try {
if (value == null) {
return monoError(logger, new NullPointerException("'value' cannot be null."));
}
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Update the attribute identified by `name` where `reference` is the name of the repository.
*
* @param value Repository attribute value.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(ContentProperties value) {
return this.setPropertiesWithResponse(value)
.flatMap((Response<Void> res) -> Mono.empty());
}
/**
* Update tag attributes.
*
* @param tag Tag name.
* @param value Repository attribute value.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setTagPropertiesWithResponse(
String tag, ContentProperties value) {
return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context));
}
Mono<Response<Void>> setTagPropertiesWithResponse(
String tag, ContentProperties value, Context context) {
try {
if (tag == null) {
return monoError(logger, new NullPointerException("'tag' cannot be null."));
}
if (value == null) {
return monoError(logger, new NullPointerException("'value' cannot be null."));
}
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Update tag attributes.
*
* @param tag Tag name.
* @param value Repository attribute value.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setTagProperties(String tag, ContentProperties value) {
return this.setTagPropertiesWithResponse(tag, value)
.flatMap((Response<Void> res) -> Mono.empty());
}
/**
* Update attributes of a manifest.
*
* @param digest Digest of a BLOB.
* @param value Repository attribute value.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setManifestPropertiesWithResponse(
String digest, ContentProperties value) {
return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context));
}
Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) {
try {
if (digest == null) {
return monoError(logger, new NullPointerException("'digest' cannot be null."));
}
if (value == null) {
return monoError(logger, new NullPointerException("'value' cannot be null."));
}
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Update attributes of a manifest.
*
* @param digest Digest of a BLOB.
* @param value Repository attribute value.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setManifestProperties(String digest, ContentProperties value) {
return this.setManifestPropertiesWithResponse(digest, value)
.flatMap((Response<Void> res) -> Mono.empty());
}
} | class ContainerRepositoryAsyncClient {
private final ContainerRegistryRepositoriesImpl serviceClient;
private final ContainerRegistriesImpl registriesImplClient;
private final String repositoryName;
private final String endpoint;
private final String apiVersion;
private final ClientLogger logger = new ClientLogger(ContainerRepositoryAsyncClient.class);
ContainerRepositoryAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String apiVersion) {
if (repositoryName == null) {
throw logger.logExceptionAsError(new NullPointerException("'repositoryName' can't be null"));
}
ContainerRegistryImpl registryImpl = new ContainerRegistryImplBuilder()
.pipeline(httpPipeline)
.url(endpoint).buildClient();
this.endpoint = endpoint;
this.repositoryName = repositoryName;
this.registriesImplClient = registryImpl.getContainerRegistries();
this.serviceClient = registryImpl.getContainerRegistryRepositories();
this.apiVersion = apiVersion;
}
/**
* Get endpoint associated with the class.
* @return String the endpoint associated with this client.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* Get the registry associated with the client.
* @return Return the registry name.
*/
public String getRegistry() {
return this.endpoint;
}
/**
* Get repository associated with the class.
* @return Return the repository name.
* */
public String getRepository() {
return this.repositoryName;
}
/**
* Delete the repository.
*
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given name was not found.
* @return deleted repository properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteWithResponse() {
return withContext(context -> deleteWithResponse(context));
}
Mono<Response<DeleteRepositoryResult>> deleteWithResponse(Context context) {
try {
return this.registriesImplClient.deleteRepositoryWithResponseAsync(repositoryName, context)
.map(res -> Utils.mapResponse(res, Utils::mapDeleteRepositoryResult))
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete the repository.
*
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given name was not found.
* @return deleted repository properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> delete() {
return this.deleteWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Delete registry artifact.
*
* @param digest the digest to delete.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @throws NullPointerException thrown if digest is null.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest) {
return withContext(context -> this.deleteRegistryArtifactWithResponse(digest, context));
}
Mono<Response<Void>> deleteRegistryArtifactWithResponse(String digest, Context context) {
try {
if (digest == null) {
return monoError(logger, new NullPointerException("'digest' cannot be null"));
}
return this.serviceClient.deleteManifestWithResponseAsync(repositoryName, digest, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete registry artifact.
*
* @param digest digest to delete.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @throws NullPointerException thrown if digest is null.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Delete tag.
*
* @param tag tag to delete.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given tag was not found.
* @throws NullPointerException thrown if tag is null.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTagWithResponse(String tag) {
return withContext(context -> this.deleteTagWithResponse(tag, context));
}
Mono<Response<Void>> deleteTagWithResponse(String tag, Context context) {
try {
if (tag == null) {
return monoError(logger, new NullPointerException("'digest' cannot be null"));
}
return this.serviceClient.deleteTagWithResponseAsync(repositoryName, tag, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete tag.
*
* @param tag tag to delete
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @throws NullPointerException thrown if tag is null.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTag(String tag) {
return this.deleteTagWithResponse(tag).flatMap(FluxUtil::toMono);
}
/**
* Get repository properties.
*
* @return repository properties.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RepositoryProperties>> getPropertiesWithResponse() {
return withContext(context -> this.getPropertiesWithResponse(context));
}
Mono<Response<RepositoryProperties>> getPropertiesWithResponse(Context context) {
try {
if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
return this.serviceClient.getPropertiesWithResponseAsync(repositoryName, context)
.map(res -> Utils.mapResponse(res, Utils::mapRepositoryProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get repository properties.
*
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given repository was not found.
* @return repository properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RepositoryProperties> getProperties() {
return this.getPropertiesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* <p>Get registry artifact properties.</p>
*
* <p>This method can take in both a digest as well as a tag.<br>
* In case a tag is provided it calls the service to get the digest associated with it.</p>
* @param tagOrDigest tag or digest associated with the artifact.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return registry artifact properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest) {
return withContext(context -> this.getRegistryArtifactPropertiesWithResponse(tagOrDigest, context));
}
Mono<Response<RegistryArtifactProperties>> getRegistryArtifactPropertiesWithResponse(String tagOrDigest, Context context) {
try {
Mono<String> getTagMono = tagOrDigest.contains(":")
? Mono.just(tagOrDigest)
: this.getTagProperties(tagOrDigest).map(a -> a.getDigest());
return getTagMono
.flatMap(digest -> this.serviceClient.getRegistryArtifactPropertiesWithResponseAsync(repositoryName, digest))
.map(res -> Utils.mapResponse(res, Utils::mapArtifactProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* <p>Get registry artifact properties.</p>
*
* <p>This method can take in both a digest as well as a tag.<br>
* In case a tag is provided it calls the service to get the digest associated with it.</p>
* @param tagOrDigest tag or digest associated with the artifact.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return registry artifact properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RegistryArtifactProperties> getRegistryArtifactProperties(String tagOrDigest) {
return this.getRegistryArtifactPropertiesWithResponse(tagOrDigest).flatMap(FluxUtil::toMono);
}
/**
* List registry artifacts of a repository.
*
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @return manifest attributes.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts() {
return listRegistryArtifacts(null);
}
/**
* List registry artifacts of a repository.
*
* @param options the options associated with the list registry operation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @return manifest attributes.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RegistryArtifactProperties> listRegistryArtifacts(ListRegistryArtifactOptions options) {
return new PagedFlux<>(
(pageSize) -> withContext(context -> listRegistryArtifactsSinglePageAsync(pageSize, options, context)),
(token, pageSize) -> withContext(context -> listRegistryArtifactsNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsSinglePageAsync(Integer pageSize, ListRegistryArtifactOptions options, Context context) {
try {
if (pageSize != null && pageSize < 0) {
return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative."));
}
String orderBy = null;
if (options != null && options.getRegistryArtifactOrderBy() != null) {
orderBy = options.getRegistryArtifactOrderBy().toString();
}
return this.serviceClient.getManifestsSinglePageAsync(repositoryName, null, pageSize, orderBy, context)
.map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<RegistryArtifactProperties>> listRegistryArtifactsNextSinglePageAsync(String nextLink, Context context) {
try {
return this.serviceClient.getManifestsNextSinglePageAsync(nextLink, context)
.map(res -> Utils.getPagedResponseWithContinuationToken(res, Utils::getRegistryArtifactsProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Get tag properties
*
* @param tag name of the tag.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given tag was not found.
* @return tag properties by tag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag) {
return withContext(context -> getTagPropertiesWithResponse(tag, context));
}
Mono<Response<TagProperties>> getTagPropertiesWithResponse(String tag, Context context) {
try {
if (tag == null) {
return monoError(logger, new NullPointerException("'tag' cannot be null."));
}
return this.serviceClient.getTagPropertiesWithResponseAsync(repositoryName, tag, context)
.map(res -> Utils.mapResponse(res, Utils::mapTagProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get tag attributes.
*
* @param tag name of the tag.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given tag was not found.
* @return tag properties by tag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TagProperties> getTagProperties(String tag) {
return this.getTagPropertiesWithResponse(tag).flatMap(FluxUtil::toMono);
}
/**
* List tags of a repository.
*
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @return list of tag details.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TagProperties> listTags() {
return listTags(null);
}
/**
* List tags of a repository.
*
* @param options tagOptions to be used for the given operation.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @return list of tag details.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TagProperties> listTags(ListTagsOptions options) {
return new PagedFlux<>(
(pageSize) -> withContext(context -> listTagsSinglePageAsync(pageSize, options, context)),
(token, pageSize) -> withContext(context -> listTagsNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<TagProperties>> listTagsSinglePageAsync(Integer pageSize, ListTagsOptions options, Context context) {
try {
if (pageSize != null && pageSize < 0) {
return monoError(logger, new IllegalArgumentException("'pageSize' cannot be negative."));
}
String orderBy = null;
if (options != null && options.getTagOrderBy() != null) {
orderBy = options.getTagOrderBy().toString();
}
return this.serviceClient.getTagsSinglePageAsync(repositoryName, null, pageSize, orderBy, null, context)
.map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties))
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
private List<TagProperties> getTagProperties(List<TagAttributesBase> baseValues) {
Objects.requireNonNull(baseValues);
return baseValues.stream().map(value -> new TagProperties(
value.getName(),
repositoryName,
value.getDigest(),
value.getWriteableProperties(),
value.getCreatedOn(),
value.getLastUpdatedOn()
)).collect(Collectors.toList());
}
Mono<PagedResponse<TagProperties>> listTagsNextSinglePageAsync(String nextLink, Context context) {
try {
return this.serviceClient.getTagsNextSinglePageAsync(nextLink, context)
.map(res -> Utils.getPagedResponseWithContinuationToken(res, this::getTagProperties));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Update the content properties of the repository.
*
* @param value Content properties to be set.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value) {
return withContext(context -> this.setPropertiesWithResponse(value, context));
}
Mono<Response<Void>> setPropertiesWithResponse(ContentProperties value, Context context) {
try {
if (value == null) {
return monoError(logger, new NullPointerException("'value' cannot be null."));
}
return this.serviceClient.setPropertiesWithResponseAsync(repositoryName, value, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Update the content properties of the repository.
*
* @param value Content properties to be set.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setProperties(ContentProperties value) {
return this.setPropertiesWithResponse(value).flatMap(FluxUtil::toMono);
}
/**
* Update tag properties.
*
* @param tag Name of the tag.
* @param value content properties to be set.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given tag was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setTagPropertiesWithResponse(
String tag, ContentProperties value) {
return withContext(context -> this.setTagPropertiesWithResponse(tag, value, context));
}
Mono<Response<Void>> setTagPropertiesWithResponse(
String tag, ContentProperties value, Context context) {
try {
if (tag == null) {
return monoError(logger, new NullPointerException("'tag' cannot be null."));
}
if (value == null) {
return monoError(logger, new NullPointerException("'value' cannot be null."));
}
return this.serviceClient.updateTagAttributesWithResponseAsync(repositoryName, tag, value, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Update tag properties.
*
* @param tag Name of the tag.
* @param value content properties to be set.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given tag was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setTagProperties(String tag, ContentProperties value) {
return this.setTagPropertiesWithResponse(tag, value).flatMap(FluxUtil::toMono);
}
/**
* Update properties of a manifest.
*
* @param digest digest.
* @param value content properties to be set.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> setManifestPropertiesWithResponse(
String digest, ContentProperties value) {
return withContext(context -> this.setManifestPropertiesWithResponse(digest, value, context));
}
Mono<Response<Void>> setManifestPropertiesWithResponse(String digest, ContentProperties value, Context context) {
try {
if (digest == null) {
return monoError(logger, new NullPointerException("'digest' cannot be null."));
}
if (value == null) {
return monoError(logger, new NullPointerException("'value' cannot be null."));
}
return this.serviceClient.updateManifestAttributesWithResponseAsync(repositoryName, digest, value, context)
.onErrorMap(Utils::mapException);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Update properties of a manifest.
*
* @param digest digest.
* @param value content properties to be set.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> setManifestProperties(String digest, ContentProperties value) {
return this.setManifestPropertiesWithResponse(digest, value).flatMap(FluxUtil::toMono);
}
} |
We generally don't log NPE mainly because we use `Objects.requireNonNull()`. It may not be a bad thing to do, just letting you know that it's not required. | public KeyEncryptionKeyClientBuilder retryPolicy(RetryPolicy retryPolicy) {
if (retryPolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'retryPolicy' cannot be null."));
}
builder.retryPolicy(retryPolicy);
return this;
} | } | public KeyEncryptionKeyClientBuilder retryPolicy(RetryPolicy retryPolicy) {
builder.retryPolicy(retryPolicy);
return this;
} | class KeyEncryptionKeyClientBuilder implements KeyEncryptionKeyResolver, AsyncKeyEncryptionKeyResolver {
private final ClientLogger logger = new ClientLogger(KeyEncryptionKeyClientBuilder.class);
private final CryptographyClientBuilder builder;
/**
* The constructor with defaults.
*/
public KeyEncryptionKeyClientBuilder() {
builder = new CryptographyClientBuilder();
}
/**
* Creates a {@link KeyEncryptionKey} based on options set in the builder. Every time
* {@code buildKeyEncryptionKey(String)} is called, a new instance of {@link KeyEncryptionKey} is created.
*
* <p>If {@link KeyEncryptionKeyClientBuilder
* and {@code keyId} are used to create the {@link KeyEncryptionKeyClient client}. All other builder settings are
* ignored. If {@code pipeline} is not set, then an
* {@link KeyEncryptionKeyClientBuilder
* are required to build the {@link KeyEncryptionKeyClient client}.</p>
*
* @return A {@link KeyEncryptionKeyClient} with the options set from the builder.
*
* @throws IllegalStateException If {@link KeyEncryptionKeyClientBuilder
* {@code keyId} have not been set.
*/
@Override
public KeyEncryptionKey buildKeyEncryptionKey(String keyId) {
return new KeyEncryptionKeyClient((KeyEncryptionKeyAsyncClient) buildAsyncKeyEncryptionKey(keyId).block());
}
/**
* Creates a {@link KeyEncryptionKeyAsyncClient} based on options set in the builder. Every time
* {@code buildAsyncKeyEncryptionKey(String)} is called, a new instance of {@link KeyEncryptionKeyAsyncClient} is
* created.
*
* <p>If {@link KeyEncryptionKeyClientBuilder
* and {@code keyId} are used to create the {@link KeyEncryptionKeyAsyncClient async client}. All other builder
* settings are ignored. If {@code pipeline} is not set, then an
* {@link KeyEncryptionKeyClientBuilder
* {@code keyId} are required to build the {@link KeyEncryptionKeyAsyncClient async client}.</p>
*
* @return A {@link KeyEncryptionKeyAsyncClient} with the options set from the builder.
*
* @throws IllegalStateException If {@link KeyEncryptionKeyClientBuilder
* {@code null} or {@code keyId} is empty or {@code null}.
*/
@Override
public Mono<? extends AsyncKeyEncryptionKey> buildAsyncKeyEncryptionKey(String keyId) {
builder.keyIdentifier(keyId);
if (Strings.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalStateException(
"An Azure Key Vault key identifier cannot be null and is required to build the key encryption key "
+ "async client."));
}
CryptographyServiceVersion serviceVersion = builder.getServiceVersion() != null ? builder.getServiceVersion() : CryptographyServiceVersion.getLatest();
if (builder.getPipeline() != null) {
return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(keyId, builder.getPipeline(), serviceVersion)));
}
if (builder.getCredential() == null) {
throw logger.logExceptionAsError(new IllegalStateException(
"Azure Key Vault credentials cannot be null and are required to build a key encryption key async "
+ "client."));
}
HttpPipeline pipeline = builder.setupPipeline();
return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(keyId, pipeline, serviceVersion)));
}
/**
* Sets the credential to use when authenticating HTTP requests.
*
* @param credential The credential to use for authenticating HTTP requests.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public KeyEncryptionKeyClientBuilder credential(TokenCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
builder.credential(credential);
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder httpLogOptions(HttpLogOptions logOptions) {
builder.httpLogOptions(logOptions);
return this;
}
/**
* Adds a policy to the set of existing policies that are executed after the client required policies.
*
* @param policy The {@link HttpPipelinePolicy policy} to be added.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public KeyEncryptionKeyClientBuilder addPolicy(HttpPipelinePolicy policy) {
if (policy == null) {
throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null."));
}
builder.addPolicy(policy);
return this;
}
/**
* Sets the HTTP client to use for sending and receiving requests to and from the service.
*
* @param client The HTTP client to use for requests.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*
* @throws NullPointerException If {@code client} is {@code null}.
*/
public KeyEncryptionKeyClientBuilder httpClient(HttpClient client) {
if (client == null) {
throw logger.logExceptionAsError(new NullPointerException("'client' cannot be null."));
}
builder.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 jsonWebKey identifier
* or jsonWebKey to build the clients.
*
* @param pipeline The HTTP pipeline to use for sending service requests and receiving responses.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*
* @throws NullPointerException If the specified {@code pipeline} is null.
*/
public KeyEncryptionKeyClientBuilder pipeline(HttpPipeline pipeline) {
if (pipeline == null) {
throw logger.logExceptionAsError(new NullPointerException("'pipeline' cannot be null."));
}
builder.pipeline(pipeline);
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the
* {@link Configuration
* bypass using configuration settings during construction.
*
* @param configuration The configuration store used to get configuration details.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder configuration(Configuration configuration) {
builder.configuration(configuration);
return this;
}
/**
* Sets the {@link CryptographyServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder serviceVersion(CryptographyServiceVersion version) {
builder.serviceVersion(version);
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent. The default retry policy will be used in
* the pipeline, if not provided.
*
* @param retryPolicy User's retry policy applied to each request.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
* Telemetry policy</a>
*
* @param clientOptions The {@link ClientOptions} to be set on the client.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder clientOptions(ClientOptions clientOptions) {
builder.clientOptions(clientOptions);
return this;
}
} | class KeyEncryptionKeyClientBuilder implements KeyEncryptionKeyResolver, AsyncKeyEncryptionKeyResolver {
private final ClientLogger logger = new ClientLogger(KeyEncryptionKeyClientBuilder.class);
private final CryptographyClientBuilder builder;
/**
* The constructor with defaults.
*/
public KeyEncryptionKeyClientBuilder() {
builder = new CryptographyClientBuilder();
}
/**
* Creates a {@link KeyEncryptionKey} based on options set in the builder. Every time
* {@code buildKeyEncryptionKey(String)} is called, a new instance of {@link KeyEncryptionKey} is created.
*
* <p>If {@link KeyEncryptionKeyClientBuilder
* and {@code keyId} are used to create the {@link KeyEncryptionKeyClient client}. All other builder settings are
* ignored. If {@code pipeline} is not set, then an
* {@link KeyEncryptionKeyClientBuilder
* are required to build the {@link KeyEncryptionKeyClient client}.</p>
*
* @return A {@link KeyEncryptionKeyClient} with the options set from the builder.
*
* @throws IllegalStateException If {@link KeyEncryptionKeyClientBuilder
* {@code keyId} have not been set.
*/
@Override
public KeyEncryptionKey buildKeyEncryptionKey(String keyId) {
return new KeyEncryptionKeyClient((KeyEncryptionKeyAsyncClient) buildAsyncKeyEncryptionKey(keyId).block());
}
/**
* Creates a {@link KeyEncryptionKeyAsyncClient} based on options set in the builder. Every time
* {@code buildAsyncKeyEncryptionKey(String)} is called, a new instance of {@link KeyEncryptionKeyAsyncClient} is
* created.
*
* <p>If {@link KeyEncryptionKeyClientBuilder
* and {@code keyId} are used to create the {@link KeyEncryptionKeyAsyncClient async client}. All other builder
* settings are ignored. If {@code pipeline} is not set, then an
* {@link KeyEncryptionKeyClientBuilder
* {@code keyId} are required to build the {@link KeyEncryptionKeyAsyncClient async client}.</p>
*
* @return A {@link KeyEncryptionKeyAsyncClient} with the options set from the builder.
*
* @throws IllegalStateException If {@link KeyEncryptionKeyClientBuilder
* {@code null} or {@code keyId} is empty or {@code null}.
*/
@Override
public Mono<? extends AsyncKeyEncryptionKey> buildAsyncKeyEncryptionKey(String keyId) {
builder.keyIdentifier(keyId);
if (Strings.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalStateException(
"An Azure Key Vault key identifier cannot be null and is required to build the key encryption key "
+ "async client."));
}
CryptographyServiceVersion serviceVersion = builder.getServiceVersion() != null ? builder.getServiceVersion() : CryptographyServiceVersion.getLatest();
if (builder.getPipeline() != null) {
return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(keyId, builder.getPipeline(), serviceVersion)));
}
if (builder.getCredential() == null) {
throw logger.logExceptionAsError(new IllegalStateException(
"Azure Key Vault credentials cannot be null and are required to build a key encryption key async "
+ "client."));
}
HttpPipeline pipeline = builder.setupPipeline();
return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(keyId, pipeline, serviceVersion)));
}
/**
* Sets the credential to use when authenticating HTTP requests.
*
* @param credential The credential to use for authenticating HTTP requests.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public KeyEncryptionKeyClientBuilder credential(TokenCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
builder.credential(credential);
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder httpLogOptions(HttpLogOptions logOptions) {
builder.httpLogOptions(logOptions);
return this;
}
/**
* Adds a policy to the set of existing policies that are executed after the client required policies.
*
* @param policy The {@link HttpPipelinePolicy policy} to be added.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public KeyEncryptionKeyClientBuilder addPolicy(HttpPipelinePolicy policy) {
if (policy == null) {
throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null."));
}
builder.addPolicy(policy);
return this;
}
/**
* Sets the HTTP client to use for sending and receiving requests to and from the service.
*
* @param client The HTTP client to use for requests.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder httpClient(HttpClient client) {
builder.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 jsonWebKey identifier
* or jsonWebKey to build the clients.
*
* @param pipeline The HTTP pipeline to use for sending service requests and receiving responses.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder pipeline(HttpPipeline pipeline) {
builder.pipeline(pipeline);
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the
* {@link Configuration
* bypass using configuration settings during construction.
*
* @param configuration The configuration store used to get configuration details.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder configuration(Configuration configuration) {
builder.configuration(configuration);
return this;
}
/**
* Sets the {@link CryptographyServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder serviceVersion(CryptographyServiceVersion version) {
builder.serviceVersion(version);
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent. The default retry policy will be used in
* the pipeline, if not provided.
*
* @param retryPolicy User's retry policy applied to each request.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
* Telemetry policy</a>
*
* @param clientOptions The {@link ClientOptions} to be set on the client.
*
* @return The updated {@link KeyEncryptionKeyClientBuilder} object.
*/
public KeyEncryptionKeyClientBuilder clientOptions(ClientOptions clientOptions) {
builder.clientOptions(clientOptions);
return this;
}
} |
Mono.error #Resolved | Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
} | throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")); | new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} |
This is a duplicate of the code in the constructor. Extract this into a method. | public AzureNamedKeyCredential update(String name, String key) {
Objects.requireNonNull(name, "'name' cannot be null.");
Objects.requireNonNull(key, "'key' cannot be null.");
if (name.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty."));
}
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
this.credentials = new AzureNamedKey(name, key);
return this;
} | this.credentials = new AzureNamedKey(name, key); | public AzureNamedKeyCredential update(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
return this;
} | class AzureNamedKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureNamedKeyCredential.class);
private volatile AzureNamedKey credentials;
/**
* Creates a credential with specified {@code name} that authorizes request with the given {@code key}.
*
* @param name The name of the key credential.
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential(String name, String key) {
Objects.requireNonNull(name, "'name' cannot be null.");
Objects.requireNonNull(key, "'key' cannot be null.");
if (name.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty."));
}
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
this.credentials = new AzureNamedKey(name, key);
}
/**
* Retrieves the {@link AzureNamedKey} containing the name and key associated with this credential.
*
* @return The {@link AzureNamedKey} containing the name and key .
*/
public AzureNamedKey getAzureNamedKey() {
return this.credentials;
}
/**
* Rotates the {@code name} and {@code key} associated to this credential.
*
* @param name The name of the key credential.
* @param key The new key to associated with this credential.
* @return The updated {@code AzureNamedKeyCredential} object.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
} | class AzureNamedKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureNamedKeyCredential.class);
private volatile AzureNamedKey credentials;
/**
* Creates a credential with specified {@code name} that authorizes request with the given {@code key}.
*
* @param name The name of the key credential.
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
}
/**
* Retrieves the {@link AzureNamedKey} containing the name and key associated with this credential.
*
* @return The {@link AzureNamedKey} containing the name and key .
*/
public AzureNamedKey getAzureNamedKey() {
return this.credentials;
}
/**
* Rotates the {@code name} and {@code key} associated to this credential.
*
* @param name The new name of the key credential.
* @param key The new key to be associated with this credential.
* @return The updated {@code AzureNamedKeyCredential} object.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
private void validateInputParameters(String name, String key) {
Objects.requireNonNull(name, "'name' cannot be null.");
Objects.requireNonNull(key, "'key' cannot be null.");
if (name.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty."));
}
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
}
} |
Should this validation be moved in `AzureNamedKey`? | private void validateInputParameters(String name, String key) {
Objects.requireNonNull(name, "'name' cannot be null.");
Objects.requireNonNull(key, "'key' cannot be null.");
if (name.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty."));
}
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
} | } | private void validateInputParameters(String name, String key) {
Objects.requireNonNull(name, "'name' cannot be null.");
Objects.requireNonNull(key, "'key' cannot be null.");
if (name.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty."));
}
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
} | class AzureNamedKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureNamedKeyCredential.class);
private volatile AzureNamedKey credentials;
/**
* Creates a credential with specified {@code name} that authorizes request with the given {@code key}.
*
* @param name The name of the key credential.
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
}
/**
* Retrieves the {@link AzureNamedKey} containing the name and key associated with this credential.
*
* @return The {@link AzureNamedKey} containing the name and key .
*/
public AzureNamedKey getAzureNamedKey() {
return this.credentials;
}
/**
* Rotates the {@code name} and {@code key} associated to this credential.
*
* @param name The new name of the key credential.
* @param key The new key to be associated with this credential.
* @return The updated {@code AzureNamedKeyCredential} object.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential update(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
return this;
}
} | class AzureNamedKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureNamedKeyCredential.class);
private volatile AzureNamedKey credentials;
/**
* Creates a credential with specified {@code name} that authorizes request with the given {@code key}.
*
* @param name The name of the key credential.
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
}
/**
* Retrieves the {@link AzureNamedKey} containing the name and key associated with this credential.
*
* @return The {@link AzureNamedKey} containing the name and key .
*/
public AzureNamedKey getAzureNamedKey() {
return this.credentials;
}
/**
* Rotates the {@code name} and {@code key} associated to this credential.
*
* @param name The new name of the key credential.
* @param key The new key to be associated with this credential.
* @return The updated {@code AzureNamedKeyCredential} object.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential update(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
return this;
}
} |
add @throws to javadoc #Resolved | public ContainerRepositoryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
} | "'credential' cannot be null."); | public ContainerRepositoryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
} | class ContainerRepositoryClientBuilder {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName");
private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion");
private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private TokenCredential credential;
private HttpPipeline httpPipeline;
private HttpLogOptions httpLogOptions;
private SerializerAdapter serializerAdapter;
private RetryPolicy retryPolicy;
private String repository;
private ContainerRegistryServiceVersion version;
/**
* Sets Registry login URL.
*
* @param endpoint the endpoint value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets repository name.
*
* @param repository name
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder repository(String repository) {
this.repository = Objects.requireNonNull(repository,
"'repository' cannot be null.");
return this;
}
/**
* Sets Registry login URL.
*
* @param credential the credential to use to access registry.
* @return the ContainerRepositoryClientBuilder.
*/
/**
* Sets The HTTP httpPipeline to send requests through.
*
* @param httpPipeline the httpPipeline value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.verbose("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the service version that will be targeted by the client.
*
* @param version the service version to target.
* @return the ContainerRegistryBuilder.
*/
public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.verbose("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
* @return The updated {@code TableClientBuilder}.
*/
public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a custom Http httpPipeline policy.
*
* @param customPolicy The custom Http httpPipeline policy to add.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null.");
if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(customPolicy);
} else {
perRetryPolicies.add(customPolicy);
}
return this;
}
/**
* Builds an instance of ContainerRegistryImpl with the provided parameters.
*
* @return an instance of ContainerRegistryImpl.
*/
public ContainerRepositoryAsyncClient buildAsyncClient() {
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
ContainerRegistryServiceVersion serviceVersion = (version != null)
? version
: ContainerRegistryServiceVersion.getLatest();
if (httpPipeline == null) {
this.httpPipeline = createHttpPipeline();
}
ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, serviceVersion.getVersion());
return client;
}
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(
new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
List<HttpHeader> httpHeaderList = new ArrayList<>();
if (clientOptions != null) {
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
}
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.add(new AddDatePolicy());
policies.addAll(this.perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
if (credential != null) {
policies.add(new ContainerRegistryCredentialsPolicy(
credential,
endpoint,
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build(),
serializerAdapter
));
}
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
/**
* Builds an instance of ContainerRegistryClient sync client.
*
* @return an instance of ContainerRegistryClient.
*/
public ContainerRepositoryClient buildClient() {
return new ContainerRepositoryClient(buildAsyncClient());
}
} | class ContainerRepositoryClientBuilder {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName");
private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion");
private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private TokenCredential credential;
private HttpPipeline httpPipeline;
private HttpLogOptions httpLogOptions;
private SerializerAdapter serializerAdapter;
private RetryPolicy retryPolicy;
private String repository;
private ContainerRegistryServiceVersion version;
/**
* Sets Registry login URL.
*
* @throws IllegalArgumentException if endpoint is not a valid URL.
* @param endpoint the endpoint value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets repository name.
* @param repository non null repository name
*
* @throws NullPointerException if repository name is null.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder repository(String repository) {
this.repository = Objects.requireNonNull(repository,
"'repository' cannot be null.");
return this;
}
/**
* Sets Registry login URL.
*
* @param credential the credential to use to access registry.
* @throws NullPointerException if credential is null.
* @return the ContainerRepositoryClientBuilder.
*/
/**
* Sets The HTTP httpPipeline to send requests through.
*
* @param httpPipeline the httpPipeline value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the service version that will be targeted by the client.
*
* @param version the service version to target.
* @return the ContainerRegistryBuilder.
*/
public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
* @return The updated {@code TableClientBuilder}.
*/
public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a custom Http httpPipeline policy.
*
* @param customPolicy The custom Http httpPipeline policy to add.
* @throws NullPointerException custom policy can't be null.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.");
if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(customPolicy);
} else {
perRetryPolicies.add(customPolicy);
}
return this;
}
/**
* Builds an instance of ContainerRegistryImpl with the provided parameters.
*
* @return an instance of ContainerRegistryImpl.
*/
public ContainerRepositoryAsyncClient buildAsyncClient() {
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
ContainerRegistryServiceVersion serviceVersion = (version != null)
? version
: ContainerRegistryServiceVersion.getLatest();
HttpPipeline pipeline = getHttpPipeline();
ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, pipeline, endpoint, serviceVersion.getVersion());
return client;
}
private HttpPipeline getHttpPipeline() {
if (httpPipeline != null) {
return httpPipeline;
}
Objects.requireNonNull(credential, "'credential' cannot be null.");
return Utils.buildHttpPipeline(
this.clientOptions,
this.httpLogOptions,
this.configuration,
this.retryPolicy,
this.credential,
this.perCallPolicies,
this.perRetryPolicies,
this.httpClient,
this.endpoint);
}
/**
* Builds an instance of ContainerRegistryClient sync client.
*
* @return an instance of ContainerRegistryClient.
*/
public ContainerRepositoryClient buildClient() {
return new ContainerRepositoryClient(buildAsyncClient());
}
} |
we can refactor it later, if and when we make its constructor public. | private void validateInputParameters(String name, String key) {
Objects.requireNonNull(name, "'name' cannot be null.");
Objects.requireNonNull(key, "'key' cannot be null.");
if (name.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty."));
}
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
} | } | private void validateInputParameters(String name, String key) {
Objects.requireNonNull(name, "'name' cannot be null.");
Objects.requireNonNull(key, "'key' cannot be null.");
if (name.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty."));
}
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
} | class AzureNamedKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureNamedKeyCredential.class);
private volatile AzureNamedKey credentials;
/**
* Creates a credential with specified {@code name} that authorizes request with the given {@code key}.
*
* @param name The name of the key credential.
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
}
/**
* Retrieves the {@link AzureNamedKey} containing the name and key associated with this credential.
*
* @return The {@link AzureNamedKey} containing the name and key .
*/
public AzureNamedKey getAzureNamedKey() {
return this.credentials;
}
/**
* Rotates the {@code name} and {@code key} associated to this credential.
*
* @param name The new name of the key credential.
* @param key The new key to be associated with this credential.
* @return The updated {@code AzureNamedKeyCredential} object.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential update(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
return this;
}
} | class AzureNamedKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureNamedKeyCredential.class);
private volatile AzureNamedKey credentials;
/**
* Creates a credential with specified {@code name} that authorizes request with the given {@code key}.
*
* @param name The name of the key credential.
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
}
/**
* Retrieves the {@link AzureNamedKey} containing the name and key associated with this credential.
*
* @return The {@link AzureNamedKey} containing the name and key .
*/
public AzureNamedKey getAzureNamedKey() {
return this.credentials;
}
/**
* Rotates the {@code name} and {@code key} associated to this credential.
*
* @param name The new name of the key credential.
* @param key The new key to be associated with this credential.
* @return The updated {@code AzureNamedKeyCredential} object.
* @throws NullPointerException If {@code key} or {@code name} is {@code null}.
* @throws IllegalArgumentException If {@code key} or {@code name} is an empty string.
*/
public AzureNamedKeyCredential update(String name, String key) {
validateInputParameters(name, key);
this.credentials = new AzureNamedKey(name, key);
return this;
}
} |
This is a code customization change where auto-import isn't able to easily resolve this, used a fully-qualified call while more functionality is added to the customization framework. | public SearchOptions setOrderBy(String... orderBy) {
this.orderBy = (orderBy == null) ? null : java.util.Arrays.asList(orderBy);
return this;
} | this.orderBy = (orderBy == null) ? null : java.util.Arrays.asList(orderBy); | public SearchOptions setOrderBy(String... orderBy) {
this.orderBy = (orderBy == null) ? null : java.util.Arrays.asList(orderBy);
return this;
} | class SearchOptions {
/*
* A value that specifies whether to fetch the total count of results.
* Default is false. Setting this value to true may have a performance
* impact. Note that the count returned is an approximation.
*/
@JsonProperty(value = "includeTotalCount")
private Boolean includeTotalCount;
/*
* The list of facet expressions to apply to the search query. Each facet
* expression contains a field name, optionally followed by a
* comma-separated list of name:value pairs.
*/
@JsonProperty(value = "Facets")
private List<String> facets;
/*
* The OData $filter expression to apply to the search query.
*/
@JsonProperty(value = "$filter")
private String filter;
/*
* The list of field names to use for hit highlights. Only searchable
* fields can be used for hit highlighting.
*/
@JsonProperty(value = "HighlightFields")
private List<String> highlightFields;
/*
* A string tag that is appended to hit highlights. Must be set with
* highlightPreTag. Default is </em>.
*/
@JsonProperty(value = "highlightPostTag")
private String highlightPostTag;
/*
* A string tag that is prepended to hit highlights. Must be set with
* highlightPostTag. Default is <em>.
*/
@JsonProperty(value = "highlightPreTag")
private String highlightPreTag;
/*
* A number between 0 and 100 indicating the percentage of the index that
* must be covered by a search query in order for the query to be reported
* as a success. This parameter can be useful for ensuring search
* availability even for services with only one replica. The default is
* 100.
*/
@JsonProperty(value = "minimumCoverage")
private Double minimumCoverage;
/*
* The list of OData $orderby expressions by which to sort the results.
* Each expression can be either a field name or a call to either the
* geo.distance() or the search.score() functions. Each expression can be
* followed by asc to indicate ascending, and desc to indicate descending.
* The default is ascending order. Ties will be broken by the match scores
* of documents. If no OrderBy is specified, the default sort order is
* descending by document match score. There can be at most 32 $orderby
* clauses.
*/
@JsonProperty(value = "OrderBy")
private List<String> orderBy;
/*
* A value that specifies the syntax of the search query. The default is
* 'simple'. Use 'full' if your query uses the Lucene query syntax.
*/
@JsonProperty(value = "queryType")
private QueryType queryType;
/*
* The list of parameter values to be used in scoring functions (for
* example, referencePointParameter) using the format name-values. For
* example, if the scoring profile defines a function with a parameter
* called 'mylocation' the parameter string would be
* "mylocation--122.2,44.8" (without the quotes).
*/
@JsonProperty(value = "ScoringParameters")
private List<String> scoringParameters;
/*
* The name of a scoring profile to evaluate match scores for matching
* documents in order to sort the results.
*/
@JsonProperty(value = "scoringProfile")
private String scoringProfile;
/*
* The list of field names to which to scope the full-text search. When
* using fielded search (fieldName:searchExpression) in a full Lucene
* query, the field names of each fielded search expression take precedence
* over any field names listed in this parameter.
*/
@JsonProperty(value = "searchFields")
private List<String> searchFields;
/*
* The language of the query.
*/
@JsonProperty(value = "queryLanguage")
private QueryLanguage queryLanguage;
/*
* Improve search recall by spell-correcting individual search query terms.
*/
@JsonProperty(value = "speller")
private QuerySpeller speller;
/*
* This parameter is only valid if the query type is 'semantic'. If set,
* the query returns answers extracted from key passages in the highest
* ranked documents. The number of answers returned can be configured by
* appending the pipe character '|' followed by the 'count-<number of
* answers>' option after the answers parameter value, such as
* 'extractive|count-3'. Default count is 1.
*/
@JsonProperty(value = "answers")
private QueryAnswer answers;
/*
* A value that specifies whether any or all of the search terms must be
* matched in order to count the document as a match.
*/
@JsonProperty(value = "searchMode")
private SearchMode searchMode;
/*
* A value that specifies whether we want to calculate scoring statistics
* (such as document frequency) globally for more consistent scoring, or
* locally, for lower latency.
*/
@JsonProperty(value = "scoringStatistics")
private ScoringStatistics scoringStatistics;
/*
* A value to be used to create a sticky session, which can help to get
* more consistent results. As long as the same sessionId is used, a
* best-effort attempt will be made to target the same replica set. Be wary
* that reusing the same sessionID values repeatedly can interfere with the
* load balancing of the requests across replicas and adversely affect the
* performance of the search service. The value used as sessionId cannot
* start with a '_' character.
*/
@JsonProperty(value = "sessionId")
private String sessionId;
/*
* The list of fields to retrieve. If unspecified, all fields marked as
* retrievable in the schema are included.
*/
@JsonProperty(value = "$select")
private List<String> select;
/*
* The number of search results to skip. This value cannot be greater than
* 100,000. If you need to scan documents in sequence, but cannot use $skip
* due to this limitation, consider using $orderby on a totally-ordered key
* and $filter with a range query instead.
*/
@JsonProperty(value = "$skip")
private Integer skip;
/*
* The number of search results to retrieve. This can be used in
* conjunction with $skip to implement client-side paging of search
* results. If results are truncated due to server-side paging, the
* response will include a continuation token that can be used to issue
* another Search request for the next page of results.
*/
@JsonProperty(value = "$top")
private Integer top;
/**
* Get the includeTotalCount property: A value that specifies whether to fetch the total count of results. Default
* is false. Setting this value to true may have a performance impact. Note that the count returned is an
* approximation.
*
* @return the includeTotalCount value.
*/
public Boolean isTotalCountIncluded() {
return this.includeTotalCount;
}
/**
* Set the includeTotalCount property: A value that specifies whether to fetch the total count of results. Default
* is false. Setting this value to true may have a performance impact. Note that the count returned is an
* approximation.
*
* @param includeTotalCount the includeTotalCount value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setIncludeTotalCount(Boolean includeTotalCount) {
this.includeTotalCount = includeTotalCount;
return this;
}
/**
* Get the facets property: The list of facet expressions to apply to the search query. Each facet expression
* contains a field name, optionally followed by a comma-separated list of name:value pairs.
*
* @return the facets value.
*/
public List<String> getFacets() {
return this.facets;
}
/**
* Set the facets property: The list of facet expressions to apply to the search query. Each facet expression
* contains a field name, optionally followed by a comma-separated list of name:value pairs.
*
* @param facets the facets value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setFacets(String... facets) {
this.facets = (facets == null) ? null : java.util.Arrays.asList(facets);
return this;
}
/**
* Get the filter property: The OData $filter expression to apply to the search query.
*
* @return the filter value.
*/
public String getFilter() {
return this.filter;
}
/**
* Set the filter property: The OData $filter expression to apply to the search query.
*
* @param filter the filter value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setFilter(String filter) {
this.filter = filter;
return this;
}
/**
* Get the highlightFields property: The list of field names to use for hit highlights. Only searchable fields can
* be used for hit highlighting.
*
* @return the highlightFields value.
*/
public List<String> getHighlightFields() {
return this.highlightFields;
}
/**
* Set the highlightFields property: The list of field names to use for hit highlights. Only searchable fields can
* be used for hit highlighting.
*
* @param highlightFields the highlightFields value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setHighlightFields(String... highlightFields) {
this.highlightFields = (highlightFields == null) ? null : java.util.Arrays.asList(highlightFields);
return this;
}
/**
* Get the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with
* highlightPreTag. Default is &lt;/em&gt;.
*
* @return the highlightPostTag value.
*/
public String getHighlightPostTag() {
return this.highlightPostTag;
}
/**
* Set the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with
* highlightPreTag. Default is &lt;/em&gt;.
*
* @param highlightPostTag the highlightPostTag value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setHighlightPostTag(String highlightPostTag) {
this.highlightPostTag = highlightPostTag;
return this;
}
/**
* Get the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with
* highlightPostTag. Default is &lt;em&gt;.
*
* @return the highlightPreTag value.
*/
public String getHighlightPreTag() {
return this.highlightPreTag;
}
/**
* Set the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with
* highlightPostTag. Default is &lt;em&gt;.
*
* @param highlightPreTag the highlightPreTag value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setHighlightPreTag(String highlightPreTag) {
this.highlightPreTag = highlightPreTag;
return this;
}
/**
* Get the minimumCoverage property: A number between 0 and 100 indicating the percentage of the index that must be
* covered by a search query in order for the query to be reported as a success. This parameter can be useful for
* ensuring search availability even for services with only one replica. The default is 100.
*
* @return the minimumCoverage value.
*/
public Double getMinimumCoverage() {
return this.minimumCoverage;
}
/**
* Set the minimumCoverage property: A number between 0 and 100 indicating the percentage of the index that must be
* covered by a search query in order for the query to be reported as a success. This parameter can be useful for
* ensuring search availability even for services with only one replica. The default is 100.
*
* @param minimumCoverage the minimumCoverage value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setMinimumCoverage(Double minimumCoverage) {
this.minimumCoverage = minimumCoverage;
return this;
}
/**
* Get the orderBy property: The list of OData $orderby expressions by which to sort the results. Each expression
* can be either a field name or a call to either the geo.distance() or the search.score() functions. Each
* expression can be followed by asc to indicate ascending, and desc to indicate descending. The default is
* ascending order. Ties will be broken by the match scores of documents. If no OrderBy is specified, the default
* sort order is descending by document match score. There can be at most 32 $orderby clauses.
*
* @return the orderBy value.
*/
public List<String> getOrderBy() {
return this.orderBy;
}
/**
* Set the orderBy property: The list of OData $orderby expressions by which to sort the results. Each expression
* can be either a field name or a call to either the geo.distance() or the search.score() functions. Each
* expression can be followed by asc to indicate ascending, and desc to indicate descending. The default is
* ascending order. Ties will be broken by the match scores of documents. If no OrderBy is specified, the default
* sort order is descending by document match score. There can be at most 32 $orderby clauses.
*
* @param orderBy the orderBy value to set.
* @return the SearchOptions object itself.
*/
/**
* Get the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use
* 'full' if your query uses the Lucene query syntax.
*
* @return the queryType value.
*/
public QueryType getQueryType() {
return this.queryType;
}
/**
* Set the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use
* 'full' if your query uses the Lucene query syntax.
*
* @param queryType the queryType value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setQueryType(QueryType queryType) {
this.queryType = queryType;
return this;
}
/**
* Get the scoringParameters property: The list of parameter values to be used in scoring functions (for example,
* referencePointParameter) using the format name-values. For example, if the scoring profile defines a function
* with a parameter called 'mylocation' the parameter string would be "mylocation--122.2,44.8" (without the quotes).
*
* @return the scoringParameters value.
*/
public List<String> getScoringParameters() {
return this.scoringParameters;
}
/**
* Set the scoringParameters property: The list of parameter values to be used in scoring functions (for example,
* referencePointParameter) using the format name-values. For example, if the scoring profile defines a function
* with a parameter called 'mylocation' the parameter string would be "mylocation--122.2,44.8" (without the quotes).
*
* @param scoringParameters the scoringParameters value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setScoringParameters(List<String> scoringParameters) {
this.scoringParameters = scoringParameters;
return this;
}
/**
* Get the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in
* order to sort the results.
*
* @return the scoringProfile value.
*/
public String getScoringProfile() {
return this.scoringProfile;
}
/**
* Set the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in
* order to sort the results.
*
* @param scoringProfile the scoringProfile value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setScoringProfile(String scoringProfile) {
this.scoringProfile = scoringProfile;
return this;
}
/**
* Get the searchFields property: The list of field names to which to scope the full-text search. When using fielded
* search (fieldName:searchExpression) in a full Lucene query, the field names of each fielded search expression
* take precedence over any field names listed in this parameter.
*
* @return the searchFields value.
*/
public List<String> getSearchFields() {
return this.searchFields;
}
/**
* Set the searchFields property: The list of field names to which to scope the full-text search. When using fielded
* search (fieldName:searchExpression) in a full Lucene query, the field names of each fielded search expression
* take precedence over any field names listed in this parameter.
*
* @param searchFields the searchFields value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSearchFields(String... searchFields) {
this.searchFields = (searchFields == null) ? null : java.util.Arrays.asList(searchFields);
return this;
}
/**
* Get the queryLanguage property: The language of the query.
*
* @return the queryLanguage value.
*/
public QueryLanguage getQueryLanguage() {
return this.queryLanguage;
}
/**
* Set the queryLanguage property: The language of the query.
*
* @param queryLanguage the queryLanguage value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setQueryLanguage(QueryLanguage queryLanguage) {
this.queryLanguage = queryLanguage;
return this;
}
/**
* Get the speller property: Improve search recall by spell-correcting individual search query terms.
*
* @return the speller value.
*/
public QuerySpeller getSpeller() {
return this.speller;
}
/**
* Set the speller property: Improve search recall by spell-correcting individual search query terms.
*
* @param speller the speller value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSpeller(QuerySpeller speller) {
this.speller = speller;
return this;
}
/**
* Get the answers property: This parameter is only valid if the query type is 'semantic'. If set, the query returns
* answers extracted from key passages in the highest ranked documents. The number of answers returned can be
* configured by appending the pipe character '|' followed by the 'count-<number of answers>' option after the
* answers parameter value, such as 'extractive|count-3'. Default count is 1.
*
* @return the answers value.
*/
public QueryAnswer getAnswers() {
return this.answers;
}
/**
* Set the answers property: This parameter is only valid if the query type is 'semantic'. If set, the query returns
* answers extracted from key passages in the highest ranked documents. The number of answers returned can be
* configured by appending the pipe character '|' followed by the 'count-<number of answers>' option after the
* answers parameter value, such as 'extractive|count-3'. Default count is 1.
*
* @param answers the answers value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setAnswers(QueryAnswer answers) {
this.answers = answers;
return this;
}
/**
* Get the searchMode property: A value that specifies whether any or all of the search terms must be matched in
* order to count the document as a match.
*
* @return the searchMode value.
*/
public SearchMode getSearchMode() {
return this.searchMode;
}
/**
* Set the searchMode property: A value that specifies whether any or all of the search terms must be matched in
* order to count the document as a match.
*
* @param searchMode the searchMode value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSearchMode(SearchMode searchMode) {
this.searchMode = searchMode;
return this;
}
/**
* Get the scoringStatistics property: A value that specifies whether we want to calculate scoring statistics (such
* as document frequency) globally for more consistent scoring, or locally, for lower latency.
*
* @return the scoringStatistics value.
*/
public ScoringStatistics getScoringStatistics() {
return this.scoringStatistics;
}
/**
* Set the scoringStatistics property: A value that specifies whether we want to calculate scoring statistics (such
* as document frequency) globally for more consistent scoring, or locally, for lower latency.
*
* @param scoringStatistics the scoringStatistics value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setScoringStatistics(ScoringStatistics scoringStatistics) {
this.scoringStatistics = scoringStatistics;
return this;
}
/**
* Get the sessionId property: A value to be used to create a sticky session, which can help to get more consistent
* results. As long as the same sessionId is used, a best-effort attempt will be made to target the same replica
* set. Be wary that reusing the same sessionID values repeatedly can interfere with the load balancing of the
* requests across replicas and adversely affect the performance of the search service. The value used as sessionId
* cannot start with a '_' character.
*
* @return the sessionId value.
*/
public String getSessionId() {
return this.sessionId;
}
/**
* Set the sessionId property: A value to be used to create a sticky session, which can help to get more consistent
* results. As long as the same sessionId is used, a best-effort attempt will be made to target the same replica
* set. Be wary that reusing the same sessionID values repeatedly can interfere with the load balancing of the
* requests across replicas and adversely affect the performance of the search service. The value used as sessionId
* cannot start with a '_' character.
*
* @param sessionId the sessionId value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSessionId(String sessionId) {
this.sessionId = sessionId;
return this;
}
/**
* Get the select property: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the
* schema are included.
*
* @return the select value.
*/
public List<String> getSelect() {
return this.select;
}
/**
* Set the select property: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the
* schema are included.
*
* @param select the select value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSelect(String... select) {
this.select = (select == null) ? null : java.util.Arrays.asList(select);
return this;
}
/**
* Get the skip property: The number of search results to skip. This value cannot be greater than 100,000. If you
* need to scan documents in sequence, but cannot use $skip due to this limitation, consider using $orderby on a
* totally-ordered key and $filter with a range query instead.
*
* @return the skip value.
*/
public Integer getSkip() {
return this.skip;
}
/**
* Set the skip property: The number of search results to skip. This value cannot be greater than 100,000. If you
* need to scan documents in sequence, but cannot use $skip due to this limitation, consider using $orderby on a
* totally-ordered key and $filter with a range query instead.
*
* @param skip the skip value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSkip(Integer skip) {
this.skip = skip;
return this;
}
/**
* Get the top property: The number of search results to retrieve. This can be used in conjunction with $skip to
* implement client-side paging of search results. If results are truncated due to server-side paging, the response
* will include a continuation token that can be used to issue another Search request for the next page of results.
*
* @return the top value.
*/
public Integer getTop() {
return this.top;
}
/**
* Set the top property: The number of search results to retrieve. This can be used in conjunction with $skip to
* implement client-side paging of search results. If results are truncated due to server-side paging, the response
* will include a continuation token that can be used to issue another Search request for the next page of results.
*
* @param top the top value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setTop(Integer top) {
this.top = top;
return this;
}
} | class SearchOptions {
/*
* A value that specifies whether to fetch the total count of results.
* Default is false. Setting this value to true may have a performance
* impact. Note that the count returned is an approximation.
*/
@JsonProperty(value = "includeTotalCount")
private Boolean includeTotalCount;
/*
* The list of facet expressions to apply to the search query. Each facet
* expression contains a field name, optionally followed by a
* comma-separated list of name:value pairs.
*/
@JsonProperty(value = "Facets")
private List<String> facets;
/*
* The OData $filter expression to apply to the search query.
*/
@JsonProperty(value = "$filter")
private String filter;
/*
* The list of field names to use for hit highlights. Only searchable
* fields can be used for hit highlighting.
*/
@JsonProperty(value = "HighlightFields")
private List<String> highlightFields;
/*
* A string tag that is appended to hit highlights. Must be set with
* highlightPreTag. Default is </em>.
*/
@JsonProperty(value = "highlightPostTag")
private String highlightPostTag;
/*
* A string tag that is prepended to hit highlights. Must be set with
* highlightPostTag. Default is <em>.
*/
@JsonProperty(value = "highlightPreTag")
private String highlightPreTag;
/*
* A number between 0 and 100 indicating the percentage of the index that
* must be covered by a search query in order for the query to be reported
* as a success. This parameter can be useful for ensuring search
* availability even for services with only one replica. The default is
* 100.
*/
@JsonProperty(value = "minimumCoverage")
private Double minimumCoverage;
/*
* The list of OData $orderby expressions by which to sort the results.
* Each expression can be either a field name or a call to either the
* geo.distance() or the search.score() functions. Each expression can be
* followed by asc to indicate ascending, and desc to indicate descending.
* The default is ascending order. Ties will be broken by the match scores
* of documents. If no OrderBy is specified, the default sort order is
* descending by document match score. There can be at most 32 $orderby
* clauses.
*/
@JsonProperty(value = "OrderBy")
private List<String> orderBy;
/*
* A value that specifies the syntax of the search query. The default is
* 'simple'. Use 'full' if your query uses the Lucene query syntax.
*/
@JsonProperty(value = "queryType")
private QueryType queryType;
/*
* The list of parameter values to be used in scoring functions (for
* example, referencePointParameter) using the format name-values. For
* example, if the scoring profile defines a function with a parameter
* called 'mylocation' the parameter string would be
* "mylocation--122.2,44.8" (without the quotes).
*/
@JsonProperty(value = "ScoringParameters")
private List<String> scoringParameters;
/*
* The name of a scoring profile to evaluate match scores for matching
* documents in order to sort the results.
*/
@JsonProperty(value = "scoringProfile")
private String scoringProfile;
/*
* The list of field names to which to scope the full-text search. When
* using fielded search (fieldName:searchExpression) in a full Lucene
* query, the field names of each fielded search expression take precedence
* over any field names listed in this parameter.
*/
@JsonProperty(value = "searchFields")
private List<String> searchFields;
/*
* The language of the query.
*/
@JsonProperty(value = "queryLanguage")
private QueryLanguage queryLanguage;
/*
* Improve search recall by spell-correcting individual search query terms.
*/
@JsonProperty(value = "speller")
private QuerySpeller speller;
/*
* This parameter is only valid if the query type is 'semantic'. If set,
* the query returns answers extracted from key passages in the highest
* ranked documents. The number of answers returned can be configured by
* appending the pipe character '|' followed by the 'count-<number of
* answers>' option after the answers parameter value, such as
* 'extractive|count-3'. Default count is 1.
*/
@JsonProperty(value = "answers")
private String answers;
/*
* A value that specifies whether any or all of the search terms must be
* matched in order to count the document as a match.
*/
@JsonProperty(value = "searchMode")
private SearchMode searchMode;
/*
* A value that specifies whether we want to calculate scoring statistics
* (such as document frequency) globally for more consistent scoring, or
* locally, for lower latency.
*/
@JsonProperty(value = "scoringStatistics")
private ScoringStatistics scoringStatistics;
/*
* A value to be used to create a sticky session, which can help to get
* more consistent results. As long as the same sessionId is used, a
* best-effort attempt will be made to target the same replica set. Be wary
* that reusing the same sessionID values repeatedly can interfere with the
* load balancing of the requests across replicas and adversely affect the
* performance of the search service. The value used as sessionId cannot
* start with a '_' character.
*/
@JsonProperty(value = "sessionId")
private String sessionId;
/*
* The list of fields to retrieve. If unspecified, all fields marked as
* retrievable in the schema are included.
*/
@JsonProperty(value = "$select")
private List<String> select;
/*
* The number of search results to skip. This value cannot be greater than
* 100,000. If you need to scan documents in sequence, but cannot use $skip
* due to this limitation, consider using $orderby on a totally-ordered key
* and $filter with a range query instead.
*/
@JsonProperty(value = "$skip")
private Integer skip;
/*
* The number of search results to retrieve. This can be used in
* conjunction with $skip to implement client-side paging of search
* results. If results are truncated due to server-side paging, the
* response will include a continuation token that can be used to issue
* another Search request for the next page of results.
*/
@JsonProperty(value = "$top")
private Integer top;
/**
* Get the includeTotalCount property: A value that specifies whether to fetch the total count of results. Default
* is false. Setting this value to true may have a performance impact. Note that the count returned is an
* approximation.
*
* @return the includeTotalCount value.
*/
public Boolean isTotalCountIncluded() {
return this.includeTotalCount;
}
/**
* Set the includeTotalCount property: A value that specifies whether to fetch the total count of results. Default
* is false. Setting this value to true may have a performance impact. Note that the count returned is an
* approximation.
*
* @param includeTotalCount the includeTotalCount value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setIncludeTotalCount(Boolean includeTotalCount) {
this.includeTotalCount = includeTotalCount;
return this;
}
/**
* Get the facets property: The list of facet expressions to apply to the search query. Each facet expression
* contains a field name, optionally followed by a comma-separated list of name:value pairs.
*
* @return the facets value.
*/
public List<String> getFacets() {
return this.facets;
}
/**
* Set the facets property: The list of facet expressions to apply to the search query. Each facet expression
* contains a field name, optionally followed by a comma-separated list of name:value pairs.
*
* @param facets the facets value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setFacets(String... facets) {
this.facets = (facets == null) ? null : java.util.Arrays.asList(facets);
return this;
}
/**
* Get the filter property: The OData $filter expression to apply to the search query.
*
* @return the filter value.
*/
public String getFilter() {
return this.filter;
}
/**
* Set the filter property: The OData $filter expression to apply to the search query.
*
* @param filter the filter value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setFilter(String filter) {
this.filter = filter;
return this;
}
/**
* Get the highlightFields property: The list of field names to use for hit highlights. Only searchable fields can
* be used for hit highlighting.
*
* @return the highlightFields value.
*/
public List<String> getHighlightFields() {
return this.highlightFields;
}
/**
* Set the highlightFields property: The list of field names to use for hit highlights. Only searchable fields can
* be used for hit highlighting.
*
* @param highlightFields the highlightFields value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setHighlightFields(String... highlightFields) {
this.highlightFields = (highlightFields == null) ? null : java.util.Arrays.asList(highlightFields);
return this;
}
/**
* Get the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with
* highlightPreTag. Default is &lt;/em&gt;.
*
* @return the highlightPostTag value.
*/
public String getHighlightPostTag() {
return this.highlightPostTag;
}
/**
* Set the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with
* highlightPreTag. Default is &lt;/em&gt;.
*
* @param highlightPostTag the highlightPostTag value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setHighlightPostTag(String highlightPostTag) {
this.highlightPostTag = highlightPostTag;
return this;
}
/**
* Get the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with
* highlightPostTag. Default is &lt;em&gt;.
*
* @return the highlightPreTag value.
*/
public String getHighlightPreTag() {
return this.highlightPreTag;
}
/**
* Set the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with
* highlightPostTag. Default is &lt;em&gt;.
*
* @param highlightPreTag the highlightPreTag value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setHighlightPreTag(String highlightPreTag) {
this.highlightPreTag = highlightPreTag;
return this;
}
/**
* Get the minimumCoverage property: A number between 0 and 100 indicating the percentage of the index that must be
* covered by a search query in order for the query to be reported as a success. This parameter can be useful for
* ensuring search availability even for services with only one replica. The default is 100.
*
* @return the minimumCoverage value.
*/
public Double getMinimumCoverage() {
return this.minimumCoverage;
}
/**
* Set the minimumCoverage property: A number between 0 and 100 indicating the percentage of the index that must be
* covered by a search query in order for the query to be reported as a success. This parameter can be useful for
* ensuring search availability even for services with only one replica. The default is 100.
*
* @param minimumCoverage the minimumCoverage value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setMinimumCoverage(Double minimumCoverage) {
this.minimumCoverage = minimumCoverage;
return this;
}
/**
* Get the orderBy property: The list of OData $orderby expressions by which to sort the results. Each expression
* can be either a field name or a call to either the geo.distance() or the search.score() functions. Each
* expression can be followed by asc to indicate ascending, and desc to indicate descending. The default is
* ascending order. Ties will be broken by the match scores of documents. If no OrderBy is specified, the default
* sort order is descending by document match score. There can be at most 32 $orderby clauses.
*
* @return the orderBy value.
*/
public List<String> getOrderBy() {
return this.orderBy;
}
/**
* Set the orderBy property: The list of OData $orderby expressions by which to sort the results. Each expression
* can be either a field name or a call to either the geo.distance() or the search.score() functions. Each
* expression can be followed by asc to indicate ascending, and desc to indicate descending. The default is
* ascending order. Ties will be broken by the match scores of documents. If no OrderBy is specified, the default
* sort order is descending by document match score. There can be at most 32 $orderby clauses.
*
* @param orderBy the orderBy value to set.
* @return the SearchOptions object itself.
*/
/**
* Get the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use
* 'full' if your query uses the Lucene query syntax.
*
* @return the queryType value.
*/
public QueryType getQueryType() {
return this.queryType;
}
/**
* Set the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use
* 'full' if your query uses the Lucene query syntax.
*
* @param queryType the queryType value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setQueryType(QueryType queryType) {
this.queryType = queryType;
return this;
}
/**
* Get the scoringParameters property: The list of parameter values to be used in scoring functions (for example,
* referencePointParameter) using the format name-values. For example, if the scoring profile defines a function
* with a parameter called 'mylocation' the parameter string would be "mylocation--122.2,44.8" (without the quotes).
*
* @return the scoringParameters value.
*/
public List<String> getScoringParameters() {
return this.scoringParameters;
}
/**
* Set the scoringParameters property: The list of parameter values to be used in scoring functions (for example,
* referencePointParameter) using the format name-values. For example, if the scoring profile defines a function
* with a parameter called 'mylocation' the parameter string would be "mylocation--122.2,44.8" (without the quotes).
*
* @param scoringParameters the scoringParameters value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setScoringParameters(List<String> scoringParameters) {
this.scoringParameters = scoringParameters;
return this;
}
/**
* Get the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in
* order to sort the results.
*
* @return the scoringProfile value.
*/
public String getScoringProfile() {
return this.scoringProfile;
}
/**
* Set the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in
* order to sort the results.
*
* @param scoringProfile the scoringProfile value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setScoringProfile(String scoringProfile) {
this.scoringProfile = scoringProfile;
return this;
}
/**
* Get the searchFields property: The list of field names to which to scope the full-text search. When using fielded
* search (fieldName:searchExpression) in a full Lucene query, the field names of each fielded search expression
* take precedence over any field names listed in this parameter.
*
* @return the searchFields value.
*/
public List<String> getSearchFields() {
return this.searchFields;
}
/**
* Set the searchFields property: The list of field names to which to scope the full-text search. When using fielded
* search (fieldName:searchExpression) in a full Lucene query, the field names of each fielded search expression
* take precedence over any field names listed in this parameter.
*
* @param searchFields the searchFields value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSearchFields(String... searchFields) {
this.searchFields = (searchFields == null) ? null : java.util.Arrays.asList(searchFields);
return this;
}
/**
* Get the queryLanguage property: The language of the query.
*
* @return the queryLanguage value.
*/
public QueryLanguage getQueryLanguage() {
return this.queryLanguage;
}
/**
* Set the queryLanguage property: The language of the query.
*
* @param queryLanguage the queryLanguage value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setQueryLanguage(QueryLanguage queryLanguage) {
this.queryLanguage = queryLanguage;
return this;
}
/**
* Get the speller property: Improve search recall by spell-correcting individual search query terms.
*
* @return the speller value.
*/
public QuerySpeller getSpeller() {
return this.speller;
}
/**
* Set the speller property: Improve search recall by spell-correcting individual search query terms.
*
* @param speller the speller value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSpeller(QuerySpeller speller) {
this.speller = speller;
return this;
}
/**
* Get the answers property: This parameter is only valid if the query type is 'semantic'. If set, the query returns
* answers extracted from key passages in the highest ranked documents. The number of answers returned can be
* configured by appending the pipe character '|' followed by the 'count-<number of answers>' option after the
* answers parameter value, such as 'extractive|count-3'. Default count is 1.
*
* @return the answers value.
*/
public String getAnswers() {
return this.answers;
}
/**
* Set the answers property: This parameter is only valid if the query type is 'semantic'. If set, the query returns
* answers extracted from key passages in the highest ranked documents. The number of answers returned can be
* configured by appending the pipe character '|' followed by the 'count-<number of answers>' option after the
* answers parameter value, such as 'extractive|count-3'. Default count is 1.
*
* @param answers the answers value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setAnswers(String answers) {
this.answers = answers;
return this;
}
/**
* Get the searchMode property: A value that specifies whether any or all of the search terms must be matched in
* order to count the document as a match.
*
* @return the searchMode value.
*/
public SearchMode getSearchMode() {
return this.searchMode;
}
/**
* Set the searchMode property: A value that specifies whether any or all of the search terms must be matched in
* order to count the document as a match.
*
* @param searchMode the searchMode value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSearchMode(SearchMode searchMode) {
this.searchMode = searchMode;
return this;
}
/**
* Get the scoringStatistics property: A value that specifies whether we want to calculate scoring statistics (such
* as document frequency) globally for more consistent scoring, or locally, for lower latency.
*
* @return the scoringStatistics value.
*/
public ScoringStatistics getScoringStatistics() {
return this.scoringStatistics;
}
/**
* Set the scoringStatistics property: A value that specifies whether we want to calculate scoring statistics (such
* as document frequency) globally for more consistent scoring, or locally, for lower latency.
*
* @param scoringStatistics the scoringStatistics value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setScoringStatistics(ScoringStatistics scoringStatistics) {
this.scoringStatistics = scoringStatistics;
return this;
}
/**
* Get the sessionId property: A value to be used to create a sticky session, which can help to get more consistent
* results. As long as the same sessionId is used, a best-effort attempt will be made to target the same replica
* set. Be wary that reusing the same sessionID values repeatedly can interfere with the load balancing of the
* requests across replicas and adversely affect the performance of the search service. The value used as sessionId
* cannot start with a '_' character.
*
* @return the sessionId value.
*/
public String getSessionId() {
return this.sessionId;
}
/**
* Set the sessionId property: A value to be used to create a sticky session, which can help to get more consistent
* results. As long as the same sessionId is used, a best-effort attempt will be made to target the same replica
* set. Be wary that reusing the same sessionID values repeatedly can interfere with the load balancing of the
* requests across replicas and adversely affect the performance of the search service. The value used as sessionId
* cannot start with a '_' character.
*
* @param sessionId the sessionId value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSessionId(String sessionId) {
this.sessionId = sessionId;
return this;
}
/**
* Get the select property: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the
* schema are included.
*
* @return the select value.
*/
public List<String> getSelect() {
return this.select;
}
/**
* Set the select property: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the
* schema are included.
*
* @param select the select value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSelect(String... select) {
this.select = (select == null) ? null : java.util.Arrays.asList(select);
return this;
}
/**
* Get the skip property: The number of search results to skip. This value cannot be greater than 100,000. If you
* need to scan documents in sequence, but cannot use $skip due to this limitation, consider using $orderby on a
* totally-ordered key and $filter with a range query instead.
*
* @return the skip value.
*/
public Integer getSkip() {
return this.skip;
}
/**
* Set the skip property: The number of search results to skip. This value cannot be greater than 100,000. If you
* need to scan documents in sequence, but cannot use $skip due to this limitation, consider using $orderby on a
* totally-ordered key and $filter with a range query instead.
*
* @param skip the skip value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setSkip(Integer skip) {
this.skip = skip;
return this;
}
/**
* Get the top property: The number of search results to retrieve. This can be used in conjunction with $skip to
* implement client-side paging of search results. If results are truncated due to server-side paging, the response
* will include a continuation token that can be used to issue another Search request for the next page of results.
*
* @return the top value.
*/
public Integer getTop() {
return this.top;
}
/**
* Set the top property: The number of search results to retrieve. This can be used in conjunction with $skip to
* implement client-side paging of search results. If results are truncated due to server-side paging, the response
* will include a continuation token that can be used to issue another Search request for the next page of results.
*
* @param top the top value to set.
* @return the SearchOptions object itself.
*/
public SearchOptions setTop(Integer top) {
this.top = top;
return this;
}
} |
```suggestion Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); ``` #Resolved | public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null.");
if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(customPolicy);
} else {
perRetryPolicies.add(customPolicy);
}
return this;
} | Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null."); | public ContainerRepositoryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.");
if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(customPolicy);
} else {
perRetryPolicies.add(customPolicy);
}
return this;
} | class ContainerRepositoryClientBuilder {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName");
private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion");
private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private TokenCredential credential;
private HttpPipeline httpPipeline;
private HttpLogOptions httpLogOptions;
private SerializerAdapter serializerAdapter;
private RetryPolicy retryPolicy;
private String repository;
private ContainerRegistryServiceVersion version;
/**
* Sets Registry login URL.
*
* @param endpoint the endpoint value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets repository name.
*
* @param repository name
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder repository(String repository) {
this.repository = Objects.requireNonNull(repository,
"'repository' cannot be null.");
return this;
}
/**
* Sets Registry login URL.
*
* @param credential the credential to use to access registry.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets The HTTP httpPipeline to send requests through.
*
* @param httpPipeline the httpPipeline value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.verbose("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the service version that will be targeted by the client.
*
* @param version the service version to target.
* @return the ContainerRegistryBuilder.
*/
public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.verbose("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
* @return The updated {@code TableClientBuilder}.
*/
public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a custom Http httpPipeline policy.
*
* @param customPolicy The custom Http httpPipeline policy to add.
* @return the ContainerRepositoryClientBuilder.
*/
/**
* Builds an instance of ContainerRegistryImpl with the provided parameters.
*
* @return an instance of ContainerRegistryImpl.
*/
public ContainerRepositoryAsyncClient buildAsyncClient() {
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
ContainerRegistryServiceVersion serviceVersion = (version != null)
? version
: ContainerRegistryServiceVersion.getLatest();
if (httpPipeline == null) {
this.httpPipeline = createHttpPipeline();
}
ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, httpPipeline, serializerAdapter, endpoint, serviceVersion.getVersion());
return client;
}
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(
new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
List<HttpHeader> httpHeaderList = new ArrayList<>();
if (clientOptions != null) {
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
}
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.add(new AddDatePolicy());
policies.addAll(this.perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
if (credential != null) {
policies.add(new ContainerRegistryCredentialsPolicy(
credential,
endpoint,
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build(),
serializerAdapter
));
}
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
/**
* Builds an instance of ContainerRegistryClient sync client.
*
* @return an instance of ContainerRegistryClient.
*/
public ContainerRepositoryClient buildClient() {
return new ContainerRepositoryClient(buildAsyncClient());
}
} | class ContainerRepositoryClientBuilder {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName");
private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion");
private final ClientLogger logger = new ClientLogger(ContainerRepositoryClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private TokenCredential credential;
private HttpPipeline httpPipeline;
private HttpLogOptions httpLogOptions;
private SerializerAdapter serializerAdapter;
private RetryPolicy retryPolicy;
private String repository;
private ContainerRegistryServiceVersion version;
/**
* Sets Registry login URL.
*
* @throws IllegalArgumentException if endpoint is not a valid URL.
* @param endpoint the endpoint value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets repository name.
* @param repository non null repository name
*
* @throws NullPointerException if repository name is null.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder repository(String repository) {
this.repository = Objects.requireNonNull(repository,
"'repository' cannot be null.");
return this;
}
/**
* Sets Registry login URL.
*
* @param credential the credential to use to access registry.
* @throws NullPointerException if credential is null.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets The HTTP httpPipeline to send requests through.
*
* @param httpPipeline the httpPipeline value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the service version that will be targeted by the client.
*
* @param version the service version to target.
* @return the ContainerRegistryBuilder.
*/
public ContainerRepositoryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
* @return The updated {@code TableClientBuilder}.
*/
public ContainerRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the ContainerRepositoryClientBuilder.
*/
public ContainerRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a custom Http httpPipeline policy.
*
* @param customPolicy The custom Http httpPipeline policy to add.
* @throws NullPointerException custom policy can't be null.
* @return the ContainerRepositoryClientBuilder.
*/
/**
* Builds an instance of ContainerRegistryImpl with the provided parameters.
*
* @return an instance of ContainerRegistryImpl.
*/
public ContainerRepositoryAsyncClient buildAsyncClient() {
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
ContainerRegistryServiceVersion serviceVersion = (version != null)
? version
: ContainerRegistryServiceVersion.getLatest();
HttpPipeline pipeline = getHttpPipeline();
ContainerRepositoryAsyncClient client = new ContainerRepositoryAsyncClient(repository, pipeline, endpoint, serviceVersion.getVersion());
return client;
}
private HttpPipeline getHttpPipeline() {
if (httpPipeline != null) {
return httpPipeline;
}
Objects.requireNonNull(credential, "'credential' cannot be null.");
return Utils.buildHttpPipeline(
this.clientOptions,
this.httpLogOptions,
this.configuration,
this.retryPolicy,
this.credential,
this.perCallPolicies,
this.perRetryPolicies,
this.httpClient,
this.endpoint);
}
/**
* Builds an instance of ContainerRegistryClient sync client.
*
* @return an instance of ContainerRegistryClient.
*/
public ContainerRepositoryClient buildClient() {
return new ContainerRepositoryClient(buildAsyncClient());
}
} |
Does the entire `continuationLinkHeader` need to be contained in the pattern or only a portion? For example given the pattern `hello`, which of the following is allowed to pass this conditional: 1. `hello world` 2. `hello` If `matches` is used only #2 will return true, if `find` is used both will return true. #Resolved | private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
} | if (matcher.matches()) { | private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} |
Do we want to throw here or simply use a default instance of `ListRepositoriesOptions`? #Pending | public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
} | } | public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} |
nit: TODOs should use the pattern `TODO (<alias>)` Also mind writing an issue to follow-up on this. #Resolved | private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
} | private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | |
Would call into the API below with `Context.NONE`. #Pending | public DeleteRepositoryResult deleteRepository(String name) {
return this.asyncClient.deleteRepository(name).block();
} | return this.asyncClient.deleteRepository(name).block(); | public DeleteRepositoryResult deleteRepository(String name) {
return this.asyncClient.deleteRepository(name).block();
} | class ContainerRegistryClient {
private final ContainerRegistryAsyncClient asyncClient;
/**
* Initializes an instance of ContainerRegistries client.
*
* @param asyncClient the service client implementation.
*/
ContainerRegistryClient(ContainerRegistryAsyncClient asyncClient) {
this.asyncClient = asyncClient;
}
/**
* List repositories.
*
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories() {
return new PagedIterable<>(this.asyncClient.listRepositories());
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.containers.containerregistry.models.AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories(ListRepositoriesOptions options) {
return new PagedIterable<>(this.asyncClient.listRepositories(options));
}
/**
* List repositories.
*
* @param options The options to use while getting the list of repositories.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories(ListRepositoriesOptions options, Context context) {
Objects.requireNonNull(options);
Integer pageSize = options.getMaxPageSize();
return new PagedIterable<>(new PagedFlux<>(
() -> asyncClient.listRepositoriesSinglePageAsync(pageSize, context),
token -> asyncClient.listRepositoriesNextSinglePageAsync(token, context)));
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<DeleteRepositoryResult> deleteRepositoryWithResponse(String name, Context context) {
return this.asyncClient.deleteRepositoryWithResponse(name, context).block();
}
} | class ContainerRegistryClient {
private final ContainerRegistryAsyncClient asyncClient;
/**
* Initializes an instance of ContainerRegistries client.
*
* @param asyncClient the service client implementation.
*/
ContainerRegistryClient(ContainerRegistryAsyncClient asyncClient) {
this.asyncClient = asyncClient;
}
/**
* List repositories.
*
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories() {
return new PagedIterable<>(this.asyncClient.listRepositories());
}
/**
* List repositories.
*
* @param options The options to use while getting the list of repositories.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories(ListRepositoriesOptions options, Context context) {
Objects.requireNonNull(options);
Integer pageSize = options.getMaxPageSize();
return new PagedIterable<>(new PagedFlux<>(
() -> asyncClient.listRepositoriesSinglePageAsync(pageSize, context),
token -> asyncClient.listRepositoriesNextSinglePageAsync(token, context)));
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<DeleteRepositoryResult> deleteRepositoryWithResponse(String name, Context context) {
return this.asyncClient.deleteRepositoryWithResponse(name, context).block();
}
} |
Maybe we should make these messages `verbose` as they seem too noisy for `info` #Resolved | public ContainerRegistryClientBuilder httpPipeline(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;
} | logger.info("HttpPipeline is being set to 'null' when it was previously configured."); | public ContainerRegistryClientBuilder httpPipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.verbose("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
} | class ContainerRegistryClientBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
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 SerializerAdapter serializerAdapter;
private RetryPolicy retryPolicy;
/**
* Sets Registry login URL.
*
* @param endpoint the endpoint value.
* @return the ContainerRegistryBuilder.
*/
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 Registry login URL.
*
* @param credential the credential to use to access registry.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets The HTTP httpPipeline to send requests through.
*
* @param httpPipeline the httpPipeline value.
* @return the ContainerRegistryBuilder.
*/
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
if (this.serializerAdapter != null && serializerAdapter == null) {
logger.info("SerializerAdapter is being set to 'null' when it was previously configured.");
}
this.serializerAdapter = serializerAdapter;
return this;
}
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.error("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
* @return The updated {@code TableClientBuilder}.
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a custom Http httpPipeline policy.
*
* @param customPolicy The custom Http httpPipeline policy to add.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null.");
if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(customPolicy);
} else {
perRetryPolicies.add(customPolicy);
}
return this;
}
/**
* Builds an instance of ContainerRegistryImpl with the provided parameters.
*
* @return an instance of ContainerRegistryImpl.
*/
private ContainerRegistryImpl buildInnerClient() {
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
if (httpPipeline == null) {
this.httpPipeline = createHttpPipeline();
}
ContainerRegistryImpl client = new ContainerRegistryImpl(httpPipeline, serializerAdapter, endpoint);
return client;
}
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(
new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), SDK_NAME, SDK_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
List<HttpHeader> httpHeaderList = new ArrayList<>();
if (clientOptions != null) {
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
}
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.add(new AddDatePolicy());
policies.addAll(this.perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
if (credential != null) {
policies.add(new ContainerRegistryCredentialsPolicy(
credential,
endpoint,
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build(),
serializerAdapter
));
}
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
/**
* Builds an instance of ContainerRegistryAsyncClient async client.
*
* @return an instance of ContainerRegistryAsyncClient.
*/
public ContainerRegistryAsyncClient buildContainerRegistryAsyncClient() {
return new ContainerRegistryAsyncClient(buildInnerClient().getContainerRegistries());
}
/**
* Builds an instance of ContainerRegistryClient sync client.
*
* @return an instance of ContainerRegistryClient.
*/
public ContainerRegistryClient buildContainerRegistryClient() {
return new ContainerRegistryClient(buildContainerRegistryAsyncClient());
}
} | class ContainerRegistryClientBuilder {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName");
private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion");
private final ClientLogger logger = new ClientLogger(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 SerializerAdapter serializerAdapter;
private RetryPolicy retryPolicy;
/**
* Sets Registry login URL.
*
* @param endpoint the endpoint value.
* @return the ContainerRegistryBuilder.
*/
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 Registry login URL.
*
* @param credential the credential to use to access registry.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets The HTTP httpPipeline to send requests through.
*
* @param httpPipeline the httpPipeline value.
* @return the ContainerRegistryBuilder.
*/
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
if (this.serializerAdapter != null && serializerAdapter == null) {
logger.verbose("SerializerAdapter is being set to 'null' when it was previously configured.");
}
this.serializerAdapter = serializerAdapter;
return this;
}
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.error("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
* @return The updated {@code TableClientBuilder}.
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a custom Http httpPipeline policy.
*
* @param customPolicy The custom Http httpPipeline policy to add.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null.");
if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(customPolicy);
} else {
perRetryPolicies.add(customPolicy);
}
return this;
}
/**
* Builds an instance of ContainerRegistryImpl with the provided parameters.
*
* @return an instance of ContainerRegistryImpl.
*/
private ContainerRegistryImpl buildInnerClient() {
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
if (httpPipeline == null) {
this.httpPipeline = createHttpPipeline();
}
ContainerRegistryImpl client = new ContainerRegistryImpl(httpPipeline, serializerAdapter, endpoint);
return client;
}
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(
new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
List<HttpHeader> httpHeaderList = new ArrayList<>();
if (clientOptions != null) {
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
}
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.add(new AddDatePolicy());
policies.addAll(this.perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
if (credential != null) {
policies.add(new ContainerRegistryCredentialsPolicy(
credential,
endpoint,
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build(),
serializerAdapter
));
}
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
/**
* Builds an instance of ContainerRegistryAsyncClient async client.
*
* @return an instance of ContainerRegistryAsyncClient.
*/
public ContainerRegistryAsyncClient buildContainerRegistryAsyncClient() {
return new ContainerRegistryAsyncClient(buildInnerClient().getContainerRegistries());
}
/**
* Builds an instance of ContainerRegistryClient sync client.
*
* @return an instance of ContainerRegistryClient.
*/
public ContainerRegistryClient buildContainerRegistryClient() {
return new ContainerRegistryClient(buildContainerRegistryAsyncClient());
}
} |
SDK_NAME and SDK_VERSION should be values loaded from PROPERTIES. #Resolved | private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(
new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), SDK_NAME, SDK_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
List<HttpHeader> httpHeaderList = new ArrayList<>();
if (clientOptions != null) {
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
}
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.add(new AddDatePolicy());
policies.addAll(this.perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
if (credential != null) {
policies.add(new ContainerRegistryCredentialsPolicy(
credential,
endpoint,
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build(),
serializerAdapter
));
}
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
} | new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), SDK_NAME, SDK_VERSION, buildConfiguration)); | private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(
new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
List<HttpHeader> httpHeaderList = new ArrayList<>();
if (clientOptions != null) {
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
}
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.add(new AddDatePolicy());
policies.addAll(this.perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
if (credential != null) {
policies.add(new ContainerRegistryCredentialsPolicy(
credential,
endpoint,
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build(),
serializerAdapter
));
}
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
} | class ContainerRegistryClientBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
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 SerializerAdapter serializerAdapter;
private RetryPolicy retryPolicy;
/**
* Sets Registry login URL.
*
* @param endpoint the endpoint value.
* @return the ContainerRegistryBuilder.
*/
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 Registry login URL.
*
* @param credential the credential to use to access registry.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets The HTTP httpPipeline to send requests through.
*
* @param httpPipeline the httpPipeline value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpPipeline(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 serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
if (this.serializerAdapter != null && serializerAdapter == null) {
logger.info("SerializerAdapter is being set to 'null' when it was previously configured.");
}
this.serializerAdapter = serializerAdapter;
return this;
}
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.error("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
* @return The updated {@code TableClientBuilder}.
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a custom Http httpPipeline policy.
*
* @param customPolicy The custom Http httpPipeline policy to add.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null.");
if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(customPolicy);
} else {
perRetryPolicies.add(customPolicy);
}
return this;
}
/**
* Builds an instance of ContainerRegistryImpl with the provided parameters.
*
* @return an instance of ContainerRegistryImpl.
*/
private ContainerRegistryImpl buildInnerClient() {
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
if (httpPipeline == null) {
this.httpPipeline = createHttpPipeline();
}
ContainerRegistryImpl client = new ContainerRegistryImpl(httpPipeline, serializerAdapter, endpoint);
return client;
}
/**
* Builds an instance of ContainerRegistryAsyncClient async client.
*
* @return an instance of ContainerRegistryAsyncClient.
*/
public ContainerRegistryAsyncClient buildContainerRegistryAsyncClient() {
return new ContainerRegistryAsyncClient(buildInnerClient().getContainerRegistries());
}
/**
* Builds an instance of ContainerRegistryClient sync client.
*
* @return an instance of ContainerRegistryClient.
*/
public ContainerRegistryClient buildContainerRegistryClient() {
return new ContainerRegistryClient(buildContainerRegistryAsyncClient());
}
} | class ContainerRegistryClientBuilder {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-containers-containerregistry.properties");
private static final String CLIENT_NAME = PROPERTIES.getOrDefault("name", "UnknownName");
private static final String CLIENT_VERSION = PROPERTIES.getOrDefault("version", "UnknownVersion");
private final ClientLogger logger = new ClientLogger(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 SerializerAdapter serializerAdapter;
private RetryPolicy retryPolicy;
/**
* Sets Registry login URL.
*
* @param endpoint the endpoint value.
* @return the ContainerRegistryBuilder.
*/
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 Registry login URL.
*
* @param credential the credential to use to access registry.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential,
"'credential' cannot be null.");
return this;
}
/**
* Sets The HTTP httpPipeline to send requests through.
*
* @param httpPipeline the httpPipeline value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpPipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.verbose("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
if (this.serializerAdapter != null && serializerAdapter == null) {
logger.verbose("SerializerAdapter is being set to 'null' when it was previously configured.");
}
this.serializerAdapter = serializerAdapter;
return this;
}
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.error("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
* @return The updated {@code TableClientBuilder}.
*/
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a custom Http httpPipeline policy.
*
* @param customPolicy The custom Http httpPipeline policy to add.
* @return the ContainerRegistryBuilder.
*/
public ContainerRegistryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'pipelinePolicy' cannot be null.");
if (customPolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(customPolicy);
} else {
perRetryPolicies.add(customPolicy);
}
return this;
}
/**
* Builds an instance of ContainerRegistryImpl with the provided parameters.
*
* @return an instance of ContainerRegistryImpl.
*/
private ContainerRegistryImpl buildInnerClient() {
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
if (httpPipeline == null) {
this.httpPipeline = createHttpPipeline();
}
ContainerRegistryImpl client = new ContainerRegistryImpl(httpPipeline, serializerAdapter, endpoint);
return client;
}
/**
* Builds an instance of ContainerRegistryAsyncClient async client.
*
* @return an instance of ContainerRegistryAsyncClient.
*/
public ContainerRegistryAsyncClient buildContainerRegistryAsyncClient() {
return new ContainerRegistryAsyncClient(buildInnerClient().getContainerRegistries());
}
/**
* Builds an instance of ContainerRegistryClient sync client.
*
* @return an instance of ContainerRegistryClient.
*/
public ContainerRegistryClient buildContainerRegistryClient() {
return new ContainerRegistryClient(buildContainerRegistryAsyncClient());
}
} |
You'll want to remove this before merging as live tests will fail. I've seen something similar to this in multiple project, mind filing an issue to add infrastructure to `azure-core-test` which allows enables test proxying when an environment variable is set. #Resolved | ContainerRegistryClientBuilder getContainerRegistryBuilder(HttpClient httpClient) {
Configuration configuration = new Configuration()
.put("java.net.useSystemProxies", "true")
.put("http.proxyHost", "localhost")
.put("http.proxyPort", "8888")
.put("http.proxyUser", "1")
.put("http.proxyPassword", "1");
List<Function<String, String>> redactors = new ArrayList<>();
redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data), "REDACTED"));
ContainerRegistryClientBuilder builder = new ContainerRegistryClientBuilder()
.endpoint(getEndpoint())
.configuration(configuration)
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY))
.addPolicy(interceptorManager.getRecordPolicy(redactors));
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
return builder;
} | .put("http.proxyPassword", "1"); | ContainerRegistryClientBuilder getContainerRegistryBuilder(HttpClient httpClient) {
List<Function<String, String>> redactors = new ArrayList<>();
redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data), "REDACTED"));
ContainerRegistryClientBuilder builder = new ContainerRegistryClientBuilder()
.endpoint(getEndpoint())
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY))
.addPolicy(interceptorManager.getRecordPolicy(redactors));
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
return builder;
} | class ContainerRegistryClientTestBase extends TestBase {
private static final String AZURE_FORM_RECOGNIZER_ENDPOINT = "CONTAINERREGISTRY_ENDPOINT";
private static final String INVALID_KEY = "invalid key";
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN
= Pattern.compile("(\".*_token\":\"(.*)\".*)");
private Duration durationTestMode;
@Override
protected void beforeTest() {
if (interceptorManager.isPlaybackMode()) {
durationTestMode = ONE_NANO_DURATION;
} else {
durationTestMode = DEFAULT_POLL_INTERVAL;
}
}
static class FakeCredentials implements TokenCredential {
@Override
public Mono<AccessToken> getToken(TokenRequestContext tokenRequestContext) {
return Mono.just(new AccessToken("someFakeToken", OffsetDateTime.MAX));
}
}
protected String getEndpoint() {
return interceptorManager.isPlaybackMode() ? "https:
: Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT);
}
private String redact(String content, Matcher matcher, String replacement) {
while (matcher.find()) {
if (matcher.groupCount() == 2) {
String captureGroup = matcher.group(1);
if (!CoreUtils.isNullOrEmpty(captureGroup)) {
content = content.replace(matcher.group(2), replacement);
}
}
}
return content;
}
} | class ContainerRegistryClientTestBase extends TestBase {
private static final String AZURE_FORM_RECOGNIZER_ENDPOINT = "CONTAINERREGISTRY_ENDPOINT";
private static final String INVALID_KEY = "invalid key";
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN
= Pattern.compile("(\".*_token\":\"(.*)\".*)");
private Duration durationTestMode;
@Override
protected void beforeTest() {
if (interceptorManager.isPlaybackMode()) {
durationTestMode = ONE_NANO_DURATION;
} else {
durationTestMode = DEFAULT_POLL_INTERVAL;
}
}
static class FakeCredentials implements TokenCredential {
@Override
public Mono<AccessToken> getToken(TokenRequestContext tokenRequestContext) {
return Mono.just(new AccessToken("someFakeToken", OffsetDateTime.MAX));
}
}
protected String getEndpoint() {
return interceptorManager.isPlaybackMode() ? "https:
: Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT);
}
private String redact(String content, Matcher matcher, String replacement) {
while (matcher.find()) {
if (matcher.groupCount() == 2) {
String captureGroup = matcher.group(1);
if (!CoreUtils.isNullOrEmpty(captureGroup)) {
content = content.replace(matcher.group(2), replacement);
}
}
}
return content;
}
} |
Already done. They are working on putting the link in the response. Also, we have a work-item on our side to parse the link header along with the continuationToken in the response. --- In reply to: [602630116](https://github.com/Azure/azure-sdk-for-java/pull/20139#discussion_r602630116) [](ancestors = 602630116) | private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
} | private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | |
In this particular case yes. The entire response is in that format. --- In reply to: [602629307](https://github.com/Azure/azure-sdk-for-java/pull/20139#discussion_r602629307) [](ancestors = 602629307) | private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
} | if (matcher.matches()) { | private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} |
I actually could not get proxy to work because it needs to be passed to the httpBuilder. So, yeah azure-core-test will be the right place to have it - [https://github.com/Azure/azure-sdk-for-java/issues/20184](https://github.com/Azure/azure-sdk-for-java/issues/20184) --- In reply to: [602633935](https://github.com/Azure/azure-sdk-for-java/pull/20139#discussion_r602633935) [](ancestors = 602633935) | ContainerRegistryClientBuilder getContainerRegistryBuilder(HttpClient httpClient) {
Configuration configuration = new Configuration()
.put("java.net.useSystemProxies", "true")
.put("http.proxyHost", "localhost")
.put("http.proxyPort", "8888")
.put("http.proxyUser", "1")
.put("http.proxyPassword", "1");
List<Function<String, String>> redactors = new ArrayList<>();
redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data), "REDACTED"));
ContainerRegistryClientBuilder builder = new ContainerRegistryClientBuilder()
.endpoint(getEndpoint())
.configuration(configuration)
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY))
.addPolicy(interceptorManager.getRecordPolicy(redactors));
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
return builder;
} | .put("http.proxyPassword", "1"); | ContainerRegistryClientBuilder getContainerRegistryBuilder(HttpClient httpClient) {
List<Function<String, String>> redactors = new ArrayList<>();
redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data), "REDACTED"));
ContainerRegistryClientBuilder builder = new ContainerRegistryClientBuilder()
.endpoint(getEndpoint())
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY))
.addPolicy(interceptorManager.getRecordPolicy(redactors));
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new FakeCredentials());
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
return builder;
} | class ContainerRegistryClientTestBase extends TestBase {
private static final String AZURE_FORM_RECOGNIZER_ENDPOINT = "CONTAINERREGISTRY_ENDPOINT";
private static final String INVALID_KEY = "invalid key";
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN
= Pattern.compile("(\".*_token\":\"(.*)\".*)");
private Duration durationTestMode;
@Override
protected void beforeTest() {
if (interceptorManager.isPlaybackMode()) {
durationTestMode = ONE_NANO_DURATION;
} else {
durationTestMode = DEFAULT_POLL_INTERVAL;
}
}
static class FakeCredentials implements TokenCredential {
@Override
public Mono<AccessToken> getToken(TokenRequestContext tokenRequestContext) {
return Mono.just(new AccessToken("someFakeToken", OffsetDateTime.MAX));
}
}
protected String getEndpoint() {
return interceptorManager.isPlaybackMode() ? "https:
: Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT);
}
private String redact(String content, Matcher matcher, String replacement) {
while (matcher.find()) {
if (matcher.groupCount() == 2) {
String captureGroup = matcher.group(1);
if (!CoreUtils.isNullOrEmpty(captureGroup)) {
content = content.replace(matcher.group(2), replacement);
}
}
}
return content;
}
} | class ContainerRegistryClientTestBase extends TestBase {
private static final String AZURE_FORM_RECOGNIZER_ENDPOINT = "CONTAINERREGISTRY_ENDPOINT";
private static final String INVALID_KEY = "invalid key";
private static final Pattern JSON_PROPERTY_VALUE_REDACTION_PATTERN
= Pattern.compile("(\".*_token\":\"(.*)\".*)");
private Duration durationTestMode;
@Override
protected void beforeTest() {
if (interceptorManager.isPlaybackMode()) {
durationTestMode = ONE_NANO_DURATION;
} else {
durationTestMode = DEFAULT_POLL_INTERVAL;
}
}
static class FakeCredentials implements TokenCredential {
@Override
public Mono<AccessToken> getToken(TokenRequestContext tokenRequestContext) {
return Mono.just(new AccessToken("someFakeToken", OffsetDateTime.MAX));
}
}
protected String getEndpoint() {
return interceptorManager.isPlaybackMode() ? "https:
: Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT);
}
private String redact(String content, Matcher matcher, String replacement) {
while (matcher.find()) {
if (matcher.groupCount() == 2) {
String captureGroup = matcher.group(1);
if (!CoreUtils.isNullOrEmpty(captureGroup)) {
content = content.replace(matcher.group(2), replacement);
}
}
}
return content;
}
} |
I was looking at our SDK guidelines and it mentioned we should throw exceptions when arguments are null. Is there a common practice we follow? --- In reply to: [602629803](https://github.com/Azure/azure-sdk-for-java/pull/20139#discussion_r602629803) [](ancestors = 602629803) | public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
} | } | public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} |
I actually got this from one of the code sanity checks - may be we should also update it to give this message instead? Not sure if it is feasible. --- In reply to: [602630773](https://github.com/Azure/azure-sdk-for-java/pull/20139#discussion_r602630773) [](ancestors = 602630773) | Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
} | throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")); | Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
}
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
} |
I thought we try to have minimum code in sync clients and simply delegate things to async clients. --- In reply to: [602631431](https://github.com/Azure/azure-sdk-for-java/pull/20139#discussion_r602631431) [](ancestors = 602631431) | public DeleteRepositoryResult deleteRepository(String name) {
return this.asyncClient.deleteRepository(name).block();
} | return this.asyncClient.deleteRepository(name).block(); | public DeleteRepositoryResult deleteRepository(String name) {
return this.asyncClient.deleteRepository(name).block();
} | class ContainerRegistryClient {
private final ContainerRegistryAsyncClient asyncClient;
/**
* Initializes an instance of ContainerRegistries client.
*
* @param asyncClient the service client implementation.
*/
ContainerRegistryClient(ContainerRegistryAsyncClient asyncClient) {
this.asyncClient = asyncClient;
}
/**
* List repositories.
*
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories() {
return new PagedIterable<>(this.asyncClient.listRepositories());
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.containers.containerregistry.models.AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories(ListRepositoriesOptions options) {
return new PagedIterable<>(this.asyncClient.listRepositories(options));
}
/**
* List repositories.
*
* @param options The options to use while getting the list of repositories.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories(ListRepositoriesOptions options, Context context) {
Objects.requireNonNull(options);
Integer pageSize = options.getMaxPageSize();
return new PagedIterable<>(new PagedFlux<>(
() -> asyncClient.listRepositoriesSinglePageAsync(pageSize, context),
token -> asyncClient.listRepositoriesNextSinglePageAsync(token, context)));
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<DeleteRepositoryResult> deleteRepositoryWithResponse(String name, Context context) {
return this.asyncClient.deleteRepositoryWithResponse(name, context).block();
}
} | class ContainerRegistryClient {
private final ContainerRegistryAsyncClient asyncClient;
/**
* Initializes an instance of ContainerRegistries client.
*
* @param asyncClient the service client implementation.
*/
ContainerRegistryClient(ContainerRegistryAsyncClient asyncClient) {
this.asyncClient = asyncClient;
}
/**
* List repositories.
*
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories() {
return new PagedIterable<>(this.asyncClient.listRepositories());
}
/**
* List repositories.
*
* @param options The options to use while getting the list of repositories.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories(ListRepositoriesOptions options, Context context) {
Objects.requireNonNull(options);
Integer pageSize = options.getMaxPageSize();
return new PagedIterable<>(new PagedFlux<>(
() -> asyncClient.listRepositoriesSinglePageAsync(pageSize, context),
token -> asyncClient.listRepositoriesNextSinglePageAsync(token, context)));
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<DeleteRepositoryResult> deleteRepositoryWithResponse(String name, Context context) {
return this.asyncClient.deleteRepositoryWithResponse(name, context).block();
}
} |
We throw when null and expecting non-null. From what I could tell here the options class is a property bag that is optional (based on the default class being passed in from the simple overload). | public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
} | } | public PagedFlux<String> listRepositories(ListRepositoriesOptions options) {
if (options == null) {
throw logger.logExceptionAsError(new NullPointerException("options can't be null"));
}
Integer pageSize = options.getMaxPageSize();
return new PagedFlux<>(
() -> withContext(context -> listRepositoriesSinglePageAsync(pageSize, context)),
token -> withContext(context -> listRepositoriesNextSinglePageAsync(token, context)));
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINKHEADERNAME = "Link";
private static final String LINKMATCHER = "(<(.+)>;.*)";
private static final String ORDERBYQUERYPARAM = "&orderby=";
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINKHEADERNAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Pattern linkPattern = Pattern.compile(LINKMATCHER);
Matcher matcher = linkPattern.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(logger.logExceptionAsWarning(new IllegalArgumentException("nextLink parameter cannot be null.")));
}
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
throw logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty."));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} | class ContainerRegistryAsyncClient {
private final ContainerRegistriesImpl serviceClient;
private final ClientLogger logger = new ClientLogger(ContainerRegistryAsyncClient.class);
private static final String CONTINUATIONLINK_HEADER_NAME = "Link";
private static final String LINK_MATCHER = "(<(.+)>;.*)";
private static final Pattern CONTINUATIONLINK_PATTERN = Pattern.compile(LINK_MATCHER);
/**
* Initializes an instance of ContainerRegistries client.
*
* @param serviceClient the service client implementation.
*/
ContainerRegistryAsyncClient(ContainerRegistriesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* List repositories.
*
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<String> listRepositories() {
ListRepositoriesOptions options = new ListRepositoriesOptions();
return this.listRepositories(options);
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @return list of repositories.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws NullPointerException thrown if the parameter is null.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedResponse<String> getPagedResponseWithContinuationToken(PagedResponse<String> listRepositoriesResponse) {
String continuationLink = null;
HttpHeaders headers = listRepositoriesResponse.getHeaders();
if (headers != null) {
String continuationLinkHeader = headers.getValue(CONTINUATIONLINK_HEADER_NAME);
if (!CoreUtils.isNullOrEmpty(continuationLinkHeader)) {
Matcher matcher = CONTINUATIONLINK_PATTERN.matcher(continuationLinkHeader);
if (matcher.matches()) {
if (matcher.groupCount() == 2) {
String apiPath = matcher.group(2);
continuationLink = apiPath;
}
}
}
}
return new PagedResponseBase<String, String>(
listRepositoriesResponse.getRequest(),
listRepositoriesResponse.getStatusCode(),
listRepositoriesResponse.getHeaders(),
listRepositoriesResponse.getValue(),
continuationLink,
null
);
}
Mono<PagedResponse<String>> listRepositoriesSinglePageAsync(Integer pageSize, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesSinglePageAsync(null, pageSize, context)
.map(res -> getPagedResponseWithContinuationToken(res));
return pagedResponseMono;
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
Mono<PagedResponse<String>> listRepositoriesNextSinglePageAsync(String nextLink, Context context) {
try {
Mono<PagedResponse<String>> pagedResponseMono = this.serviceClient.listRepositoriesNextSinglePageAsync(nextLink, context);
return pagedResponseMono.map(res -> getPagedResponseWithContinuationToken(res));
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name) {
return withContext(context -> deleteRepositoryWithResponse(name, context));
}
Mono<Response<DeleteRepositoryResult>> deleteRepositoryWithResponse(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryWithResponseAsync(name, context);
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @return deleted repository.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeleteRepositoryResult> deleteRepository(String name) {
return withContext(context -> this.deleteRepository(name, context));
}
Mono<DeleteRepositoryResult> deleteRepository(String name, Context context) {
if (CoreUtils.isNullOrEmpty(name)) {
return Mono.error(logger.logExceptionAsError(new NullPointerException("repository name can't be null or empty.")));
}
return this.serviceClient.deleteRepositoryAsync(name, context);
}
} |
I've seen both flows of having {simple sync overload} -> {simple async overload} and {simple sync overload} -> {complex sync overload}. I think this is fine to leave as-is. | public DeleteRepositoryResult deleteRepository(String name) {
return this.asyncClient.deleteRepository(name).block();
} | return this.asyncClient.deleteRepository(name).block(); | public DeleteRepositoryResult deleteRepository(String name) {
return this.asyncClient.deleteRepository(name).block();
} | class ContainerRegistryClient {
private final ContainerRegistryAsyncClient asyncClient;
/**
* Initializes an instance of ContainerRegistries client.
*
* @param asyncClient the service client implementation.
*/
ContainerRegistryClient(ContainerRegistryAsyncClient asyncClient) {
this.asyncClient = asyncClient;
}
/**
* List repositories.
*
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories() {
return new PagedIterable<>(this.asyncClient.listRepositories());
}
/**
* List repositories.
*
* @param options for the list repositories call.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.containers.containerregistry.models.AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories(ListRepositoriesOptions options) {
return new PagedIterable<>(this.asyncClient.listRepositories(options));
}
/**
* List repositories.
*
* @param options The options to use while getting the list of repositories.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories(ListRepositoriesOptions options, Context context) {
Objects.requireNonNull(options);
Integer pageSize = options.getMaxPageSize();
return new PagedIterable<>(new PagedFlux<>(
() -> asyncClient.listRepositoriesSinglePageAsync(pageSize, context),
token -> asyncClient.listRepositoriesNextSinglePageAsync(token, context)));
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<DeleteRepositoryResult> deleteRepositoryWithResponse(String name, Context context) {
return this.asyncClient.deleteRepositoryWithResponse(name, context).block();
}
} | class ContainerRegistryClient {
private final ContainerRegistryAsyncClient asyncClient;
/**
* Initializes an instance of ContainerRegistries client.
*
* @param asyncClient the service client implementation.
*/
ContainerRegistryClient(ContainerRegistryAsyncClient asyncClient) {
this.asyncClient = asyncClient;
}
/**
* List repositories.
*
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories() {
return new PagedIterable<>(this.asyncClient.listRepositories());
}
/**
* List repositories.
*
* @param options The options to use while getting the list of repositories.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of repositories.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<String> listRepositories(ListRepositoriesOptions options, Context context) {
Objects.requireNonNull(options);
Integer pageSize = options.getMaxPageSize();
return new PagedIterable<>(new PagedFlux<>(
() -> asyncClient.listRepositoriesSinglePageAsync(pageSize, context),
token -> asyncClient.listRepositoriesNextSinglePageAsync(token, context)));
}
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Delete the repository identified by `name`.
*
* @param name Name of the image (including the namespace).
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws AcrErrorsException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return deleted repository.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<DeleteRepositoryResult> deleteRepositoryWithResponse(String name, Context context) {
return this.asyncClient.deleteRepositoryWithResponse(name, context).block();
}
} |
This overload is used only when there is a single page to retrieve. So, why is the pageSize required? | public PagedFlux(Function<Integer, Mono<PagedResponse<T>>> firstPageRetriever) {
this(firstPageRetriever, (token, pageSize) -> Mono.empty());
} | } | public PagedFlux(Function<Integer, Mono<PagedResponse<T>>> firstPageRetriever) {
this(firstPageRetriever, (token, pageSize) -> Mono.empty());
} | class PagedFlux<T> extends PagedFluxBase<T, PagedResponse<T>> {
/**
* Creates an instance of {@link PagedFlux} that consists of only a single page. This constructor takes a {@code
* Supplier} that return the single page of {@code T}.
*
* <p><strong>Code sample</strong></p>
* {@codesnippet com.azure.core.http.rest.pagedflux.singlepage.instantiation}
*
* @param firstPageRetriever Supplier that retrieves the first page.
*/
public PagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever) {
this(firstPageRetriever, token -> Mono.empty());
}
/**
* Creates an instance of {@link PagedFlux} that consists of only a single page with a given element count.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.PagedFlux.singlepage.instantiationWithPageSize}
*
* @param firstPageRetriever Function that retrieves the first page.
*/
/**
* Creates an instance of {@link PagedFlux}. The constructor takes a {@code Supplier} and {@code Function}. The
* {@code Supplier} returns the first page of {@code T}, the {@code Function} retrieves subsequent pages of {@code
* T}.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.pagedflux.instantiation}
*
* @param firstPageRetriever Supplier that retrieves the first page
* @param nextPageRetriever Function that retrieves the next page given a continuation token
*/
public PagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever,
Function<String, Mono<PagedResponse<T>>> nextPageRetriever) {
this(() -> (continuationToken, pageSize) -> continuationToken == null
? firstPageRetriever.get().flux()
: nextPageRetriever.apply(continuationToken).flux(), true);
}
/**
* Creates an instance of {@link PagedFlux} that is capable of retrieving multiple pages with of a given page size.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.PagedFlux.instantiationWithPageSize}
*
* @param firstPageRetriever Function that retrieves the first page.
* @param nextPageRetriever BiFunction that retrieves the next page given a continuation token.
*/
public PagedFlux(Function<Integer, Mono<PagedResponse<T>>> firstPageRetriever,
BiFunction<String, Integer, Mono<PagedResponse<T>>> nextPageRetriever) {
this(() -> (continuationToken, pageSize) -> continuationToken == null
? firstPageRetriever.apply(pageSize).flux()
: nextPageRetriever.apply(continuationToken, pageSize).flux(), true);
}
/**
* Create PagedFlux backed by Page Retriever Function Supplier.
*
* @param provider the Page Retrieval Provider
* @param ignored param is ignored, exists in signature only to avoid conflict with first ctr
*/
private PagedFlux(Supplier<PageRetriever<String, PagedResponse<T>>> provider, boolean ignored) {
super(provider, ignored);
}
/**
* Creates an instance of {@link PagedFlux} backed by a Page Retriever Supplier (provider). When invoked provider
* should return {@link PageRetriever}. The provider will be called for each Subscription to the PagedFlux instance.
* The Page Retriever can get called multiple times in serial fashion, each time after the completion of the Flux
* returned from the previous invocation. The final completion signal will be send to the Subscriber when the last
* Page emitted by the Flux returned by Page Retriever has {@code null} continuation token.
*
* The provider is useful mainly in two scenarios:
* <ul>
* <li> To manage state across multiple call to Page Retrieval within the same Subscription.
* <li> To decorate a PagedFlux to produce new PagedFlux.
* </ul>
*
* <p><strong>Decoration sample</strong></p>
* {@codesnippet com.azure.core.http.rest.pagedflux.create.decoration}
*
* @param provider the Page Retrieval Provider
* @param <T> The type of items in a {@link PagedResponse}
* @return PagedFlux backed by the Page Retriever Function Supplier
*/
public static <T> PagedFlux<T> create(Supplier<PageRetriever<String, PagedResponse<T>>> provider) {
return new PagedFlux<>(provider, true);
}
/**
* Maps this PagedFlux instance of T to a PagedFlux instance of type S as per the provided mapper function.
*
* @param mapper The mapper function to convert from type T to type S.
* @param <S> The mapped type.
* @return A PagedFlux of type S.
* @deprecated refer the decoration samples for {@link PagedFlux
*/
@Deprecated
public <S> PagedFlux<S> mapPage(Function<T, S> mapper) {
Supplier<PageRetriever<String, PagedResponse<S>>> provider = () -> (continuationToken, pageSize) -> {
Flux<PagedResponse<T>> flux = (continuationToken == null)
? byPage()
: byPage(continuationToken);
return flux.map(mapPagedResponse(mapper));
};
return PagedFlux.create(provider);
}
private <S> Function<PagedResponse<T>, PagedResponse<S>> mapPagedResponse(Function<T, S> mapper) {
return pagedResponse -> new PagedResponseBase<HttpRequest, S>(pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue().stream().map(mapper).collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null);
}
} | class PagedFlux<T> extends PagedFluxBase<T, PagedResponse<T>> {
/**
* Creates an instance of {@link PagedFlux} that consists of only a single page. This constructor takes a {@code
* Supplier} that return the single page of {@code T}.
*
* <p><strong>Code sample</strong></p>
* {@codesnippet com.azure.core.http.rest.pagedflux.singlepage.instantiation}
*
* @param firstPageRetriever Supplier that retrieves the first page.
*/
public PagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever) {
this(firstPageRetriever, token -> Mono.empty());
}
/**
* Creates an instance of {@link PagedFlux} that consists of only a single page with a given element count.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.PagedFlux.singlepage.instantiationWithPageSize}
*
* @param firstPageRetriever Function that retrieves the first page.
*/
/**
* Creates an instance of {@link PagedFlux}. The constructor takes a {@code Supplier} and {@code Function}. The
* {@code Supplier} returns the first page of {@code T}, the {@code Function} retrieves subsequent pages of {@code
* T}.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.pagedflux.instantiation}
*
* @param firstPageRetriever Supplier that retrieves the first page
* @param nextPageRetriever Function that retrieves the next page given a continuation token
*/
public PagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever,
Function<String, Mono<PagedResponse<T>>> nextPageRetriever) {
this(() -> (continuationToken, pageSize) -> continuationToken == null
? firstPageRetriever.get().flux()
: nextPageRetriever.apply(continuationToken).flux(), true);
}
/**
* Creates an instance of {@link PagedFlux} that is capable of retrieving multiple pages with of a given page size.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.PagedFlux.instantiationWithPageSize}
*
* @param firstPageRetriever Function that retrieves the first page.
* @param nextPageRetriever BiFunction that retrieves the next page given a continuation token and page size.
*/
public PagedFlux(Function<Integer, Mono<PagedResponse<T>>> firstPageRetriever,
BiFunction<String, Integer, Mono<PagedResponse<T>>> nextPageRetriever) {
this(() -> (continuationToken, pageSize) -> continuationToken == null
? firstPageRetriever.apply(pageSize).flux()
: nextPageRetriever.apply(continuationToken, pageSize).flux(), true);
}
/**
* Create PagedFlux backed by Page Retriever Function Supplier.
*
* @param provider the Page Retrieval Provider
* @param ignored param is ignored, exists in signature only to avoid conflict with first ctr
*/
private PagedFlux(Supplier<PageRetriever<String, PagedResponse<T>>> provider, boolean ignored) {
super(provider, ignored);
}
/**
* Creates an instance of {@link PagedFlux} backed by a Page Retriever Supplier (provider). When invoked provider
* should return {@link PageRetriever}. The provider will be called for each Subscription to the PagedFlux instance.
* The Page Retriever can get called multiple times in serial fashion, each time after the completion of the Flux
* returned from the previous invocation. The final completion signal will be send to the Subscriber when the last
* Page emitted by the Flux returned by Page Retriever has {@code null} continuation token.
*
* The provider is useful mainly in two scenarios:
* <ul>
* <li> To manage state across multiple call to Page Retrieval within the same Subscription.
* <li> To decorate a PagedFlux to produce new PagedFlux.
* </ul>
*
* <p><strong>Decoration sample</strong></p>
* {@codesnippet com.azure.core.http.rest.pagedflux.create.decoration}
*
* @param provider the Page Retrieval Provider
* @param <T> The type of items in a {@link PagedResponse}
* @return PagedFlux backed by the Page Retriever Function Supplier
*/
public static <T> PagedFlux<T> create(Supplier<PageRetriever<String, PagedResponse<T>>> provider) {
return new PagedFlux<>(provider, true);
}
/**
* Maps this PagedFlux instance of T to a PagedFlux instance of type S as per the provided mapper function.
*
* @param mapper The mapper function to convert from type T to type S.
* @param <S> The mapped type.
* @return A PagedFlux of type S.
* @deprecated refer the decoration samples for {@link PagedFlux
*/
@Deprecated
public <S> PagedFlux<S> mapPage(Function<T, S> mapper) {
Supplier<PageRetriever<String, PagedResponse<S>>> provider = () -> (continuationToken, pageSize) -> {
Flux<PagedResponse<T>> flux = (continuationToken == null)
? byPage()
: byPage(continuationToken);
return flux.map(mapPagedResponse(mapper));
};
return PagedFlux.create(provider);
}
private <S> Function<PagedResponse<T>, PagedResponse<S>> mapPagedResponse(Function<T, S> mapper) {
return pagedResponse -> new PagedResponseBase<HttpRequest, S>(pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue().stream().map(mapper).collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null);
}
} |
There are single paged response API, such as [Azure Search Autocomplete](https://docs.microsoft.com/en-us/rest/api/searchservice/autocomplete) and [Azure Search Suggestions](https://docs.microsoft.com/en-us/rest/api/searchservice/suggestions), which have the option of page size, or response element count. This is to enable support of those if `byPage(int preferredPageSize)` is used in the `PagedFlux`. | public PagedFlux(Function<Integer, Mono<PagedResponse<T>>> firstPageRetriever) {
this(firstPageRetriever, (token, pageSize) -> Mono.empty());
} | } | public PagedFlux(Function<Integer, Mono<PagedResponse<T>>> firstPageRetriever) {
this(firstPageRetriever, (token, pageSize) -> Mono.empty());
} | class PagedFlux<T> extends PagedFluxBase<T, PagedResponse<T>> {
/**
* Creates an instance of {@link PagedFlux} that consists of only a single page. This constructor takes a {@code
* Supplier} that return the single page of {@code T}.
*
* <p><strong>Code sample</strong></p>
* {@codesnippet com.azure.core.http.rest.pagedflux.singlepage.instantiation}
*
* @param firstPageRetriever Supplier that retrieves the first page.
*/
public PagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever) {
this(firstPageRetriever, token -> Mono.empty());
}
/**
* Creates an instance of {@link PagedFlux} that consists of only a single page with a given element count.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.PagedFlux.singlepage.instantiationWithPageSize}
*
* @param firstPageRetriever Function that retrieves the first page.
*/
/**
* Creates an instance of {@link PagedFlux}. The constructor takes a {@code Supplier} and {@code Function}. The
* {@code Supplier} returns the first page of {@code T}, the {@code Function} retrieves subsequent pages of {@code
* T}.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.pagedflux.instantiation}
*
* @param firstPageRetriever Supplier that retrieves the first page
* @param nextPageRetriever Function that retrieves the next page given a continuation token
*/
public PagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever,
Function<String, Mono<PagedResponse<T>>> nextPageRetriever) {
this(() -> (continuationToken, pageSize) -> continuationToken == null
? firstPageRetriever.get().flux()
: nextPageRetriever.apply(continuationToken).flux(), true);
}
/**
* Creates an instance of {@link PagedFlux} that is capable of retrieving multiple pages with of a given page size.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.PagedFlux.instantiationWithPageSize}
*
* @param firstPageRetriever Function that retrieves the first page.
* @param nextPageRetriever BiFunction that retrieves the next page given a continuation token.
*/
public PagedFlux(Function<Integer, Mono<PagedResponse<T>>> firstPageRetriever,
BiFunction<String, Integer, Mono<PagedResponse<T>>> nextPageRetriever) {
this(() -> (continuationToken, pageSize) -> continuationToken == null
? firstPageRetriever.apply(pageSize).flux()
: nextPageRetriever.apply(continuationToken, pageSize).flux(), true);
}
/**
* Create PagedFlux backed by Page Retriever Function Supplier.
*
* @param provider the Page Retrieval Provider
* @param ignored param is ignored, exists in signature only to avoid conflict with first ctr
*/
private PagedFlux(Supplier<PageRetriever<String, PagedResponse<T>>> provider, boolean ignored) {
super(provider, ignored);
}
/**
* Creates an instance of {@link PagedFlux} backed by a Page Retriever Supplier (provider). When invoked provider
* should return {@link PageRetriever}. The provider will be called for each Subscription to the PagedFlux instance.
* The Page Retriever can get called multiple times in serial fashion, each time after the completion of the Flux
* returned from the previous invocation. The final completion signal will be send to the Subscriber when the last
* Page emitted by the Flux returned by Page Retriever has {@code null} continuation token.
*
* The provider is useful mainly in two scenarios:
* <ul>
* <li> To manage state across multiple call to Page Retrieval within the same Subscription.
* <li> To decorate a PagedFlux to produce new PagedFlux.
* </ul>
*
* <p><strong>Decoration sample</strong></p>
* {@codesnippet com.azure.core.http.rest.pagedflux.create.decoration}
*
* @param provider the Page Retrieval Provider
* @param <T> The type of items in a {@link PagedResponse}
* @return PagedFlux backed by the Page Retriever Function Supplier
*/
public static <T> PagedFlux<T> create(Supplier<PageRetriever<String, PagedResponse<T>>> provider) {
return new PagedFlux<>(provider, true);
}
/**
* Maps this PagedFlux instance of T to a PagedFlux instance of type S as per the provided mapper function.
*
* @param mapper The mapper function to convert from type T to type S.
* @param <S> The mapped type.
* @return A PagedFlux of type S.
* @deprecated refer the decoration samples for {@link PagedFlux
*/
@Deprecated
public <S> PagedFlux<S> mapPage(Function<T, S> mapper) {
Supplier<PageRetriever<String, PagedResponse<S>>> provider = () -> (continuationToken, pageSize) -> {
Flux<PagedResponse<T>> flux = (continuationToken == null)
? byPage()
: byPage(continuationToken);
return flux.map(mapPagedResponse(mapper));
};
return PagedFlux.create(provider);
}
private <S> Function<PagedResponse<T>, PagedResponse<S>> mapPagedResponse(Function<T, S> mapper) {
return pagedResponse -> new PagedResponseBase<HttpRequest, S>(pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue().stream().map(mapper).collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null);
}
} | class PagedFlux<T> extends PagedFluxBase<T, PagedResponse<T>> {
/**
* Creates an instance of {@link PagedFlux} that consists of only a single page. This constructor takes a {@code
* Supplier} that return the single page of {@code T}.
*
* <p><strong>Code sample</strong></p>
* {@codesnippet com.azure.core.http.rest.pagedflux.singlepage.instantiation}
*
* @param firstPageRetriever Supplier that retrieves the first page.
*/
public PagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever) {
this(firstPageRetriever, token -> Mono.empty());
}
/**
* Creates an instance of {@link PagedFlux} that consists of only a single page with a given element count.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.PagedFlux.singlepage.instantiationWithPageSize}
*
* @param firstPageRetriever Function that retrieves the first page.
*/
/**
* Creates an instance of {@link PagedFlux}. The constructor takes a {@code Supplier} and {@code Function}. The
* {@code Supplier} returns the first page of {@code T}, the {@code Function} retrieves subsequent pages of {@code
* T}.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.pagedflux.instantiation}
*
* @param firstPageRetriever Supplier that retrieves the first page
* @param nextPageRetriever Function that retrieves the next page given a continuation token
*/
public PagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever,
Function<String, Mono<PagedResponse<T>>> nextPageRetriever) {
this(() -> (continuationToken, pageSize) -> continuationToken == null
? firstPageRetriever.get().flux()
: nextPageRetriever.apply(continuationToken).flux(), true);
}
/**
* Creates an instance of {@link PagedFlux} that is capable of retrieving multiple pages with of a given page size.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.core.http.rest.PagedFlux.instantiationWithPageSize}
*
* @param firstPageRetriever Function that retrieves the first page.
* @param nextPageRetriever BiFunction that retrieves the next page given a continuation token and page size.
*/
public PagedFlux(Function<Integer, Mono<PagedResponse<T>>> firstPageRetriever,
BiFunction<String, Integer, Mono<PagedResponse<T>>> nextPageRetriever) {
this(() -> (continuationToken, pageSize) -> continuationToken == null
? firstPageRetriever.apply(pageSize).flux()
: nextPageRetriever.apply(continuationToken, pageSize).flux(), true);
}
/**
* Create PagedFlux backed by Page Retriever Function Supplier.
*
* @param provider the Page Retrieval Provider
* @param ignored param is ignored, exists in signature only to avoid conflict with first ctr
*/
private PagedFlux(Supplier<PageRetriever<String, PagedResponse<T>>> provider, boolean ignored) {
super(provider, ignored);
}
/**
* Creates an instance of {@link PagedFlux} backed by a Page Retriever Supplier (provider). When invoked provider
* should return {@link PageRetriever}. The provider will be called for each Subscription to the PagedFlux instance.
* The Page Retriever can get called multiple times in serial fashion, each time after the completion of the Flux
* returned from the previous invocation. The final completion signal will be send to the Subscriber when the last
* Page emitted by the Flux returned by Page Retriever has {@code null} continuation token.
*
* The provider is useful mainly in two scenarios:
* <ul>
* <li> To manage state across multiple call to Page Retrieval within the same Subscription.
* <li> To decorate a PagedFlux to produce new PagedFlux.
* </ul>
*
* <p><strong>Decoration sample</strong></p>
* {@codesnippet com.azure.core.http.rest.pagedflux.create.decoration}
*
* @param provider the Page Retrieval Provider
* @param <T> The type of items in a {@link PagedResponse}
* @return PagedFlux backed by the Page Retriever Function Supplier
*/
public static <T> PagedFlux<T> create(Supplier<PageRetriever<String, PagedResponse<T>>> provider) {
return new PagedFlux<>(provider, true);
}
/**
* Maps this PagedFlux instance of T to a PagedFlux instance of type S as per the provided mapper function.
*
* @param mapper The mapper function to convert from type T to type S.
* @param <S> The mapped type.
* @return A PagedFlux of type S.
* @deprecated refer the decoration samples for {@link PagedFlux
*/
@Deprecated
public <S> PagedFlux<S> mapPage(Function<T, S> mapper) {
Supplier<PageRetriever<String, PagedResponse<S>>> provider = () -> (continuationToken, pageSize) -> {
Flux<PagedResponse<T>> flux = (continuationToken == null)
? byPage()
: byPage(continuationToken);
return flux.map(mapPagedResponse(mapper));
};
return PagedFlux.create(provider);
}
private <S> Function<PagedResponse<T>, PagedResponse<S>> mapPagedResponse(Function<T, S> mapper) {
return pagedResponse -> new PagedResponseBase<HttpRequest, S>(pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue().stream().map(mapper).collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null);
}
} |
Should we need to assert anything on this foreach? | public void run() {
super.metricsAdvisorClient
.listAnomaliesForAlert(super.alertConfigId,
super.alertId,
new ListAnomaliesAlertedOptions().setTop(MAX_LIST_ELEMENTS),
Context.NONE)
.forEach(anomaly -> {
});
} | }); | public void run() {
super.metricsAdvisorClient
.listAnomaliesForAlert(super.alertConfigId,
super.alertId,
new ListAnomaliesAlertedOptions(),
Context.NONE)
.stream()
.limit(super.maxListElements)
.forEach(anomaly -> {
});
} | class AnomaliesListTest extends MetricsAdvisorTestBase<PerfStressOptions> {
private static final int MAX_LIST_ELEMENTS = 10;
/**
* Creates AnomaliesListTest object.
*
* @param options the configurable options for perf testing this class.
*/
public AnomaliesListTest(PerfStressOptions options) {
super(options);
}
@Override
@Override
public Mono<Void> runAsync() {
return super.metricsAdvisorAsyncClient
.listAnomaliesForAlert(super.alertConfigId,
super.alertId,
new ListAnomaliesAlertedOptions().setTop(MAX_LIST_ELEMENTS))
.then();
}
} | class AnomaliesListTest extends ServiceTest<PerfStressOptions> {
/**
* Creates AnomaliesListTest object.
*
* @param options the configurable options for perf testing this class.
*/
public AnomaliesListTest(PerfStressOptions options) {
super(options);
}
@Override
@Override
public Mono<Void> runAsync() {
return super.metricsAdvisorAsyncClient
.listAnomaliesForAlert(super.alertConfigId,
super.alertId,
new ListAnomaliesAlertedOptions())
.take(super.maxListElements)
.then();
}
} |
I think we just have to ensure all the items are consumed, in case multi-page involved, so a foreach will do. (see the azure-storage blob list perf test) | public void run() {
super.metricsAdvisorClient
.listAnomaliesForAlert(super.alertConfigId,
super.alertId,
new ListAnomaliesAlertedOptions().setTop(MAX_LIST_ELEMENTS),
Context.NONE)
.forEach(anomaly -> {
});
} | }); | public void run() {
super.metricsAdvisorClient
.listAnomaliesForAlert(super.alertConfigId,
super.alertId,
new ListAnomaliesAlertedOptions(),
Context.NONE)
.stream()
.limit(super.maxListElements)
.forEach(anomaly -> {
});
} | class AnomaliesListTest extends MetricsAdvisorTestBase<PerfStressOptions> {
private static final int MAX_LIST_ELEMENTS = 10;
/**
* Creates AnomaliesListTest object.
*
* @param options the configurable options for perf testing this class.
*/
public AnomaliesListTest(PerfStressOptions options) {
super(options);
}
@Override
@Override
public Mono<Void> runAsync() {
return super.metricsAdvisorAsyncClient
.listAnomaliesForAlert(super.alertConfigId,
super.alertId,
new ListAnomaliesAlertedOptions().setTop(MAX_LIST_ELEMENTS))
.then();
}
} | class AnomaliesListTest extends ServiceTest<PerfStressOptions> {
/**
* Creates AnomaliesListTest object.
*
* @param options the configurable options for perf testing this class.
*/
public AnomaliesListTest(PerfStressOptions options) {
super(options);
}
@Override
@Override
public Mono<Void> runAsync() {
return super.metricsAdvisorAsyncClient
.listAnomaliesForAlert(super.alertConfigId,
super.alertId,
new ListAnomaliesAlertedOptions())
.take(super.maxListElements)
.then();
}
} |
instead of using env vars, to pass in these properties for test scenarios, use the options bag. Create your custom options bag which extends from PerfStressOptions and pass those in your Perf Test classes that extend the Service Test Class. OPtions bag will allow you to consume options from command line instead of env var and will align the usage across languages. | public ServiceTest(TOptions options) {
super(options);
final String endpoint = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_ENDPOINT");
if (CoreUtils.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_ENDPOINT")));
}
final String subscriptionKey = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_SUBSCRIPTION_KEY");
if (CoreUtils.isNullOrEmpty(subscriptionKey)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_SUBSCRIPTION_KEY")));
}
final String apiKey = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_API_KEY");
if (CoreUtils.isNullOrEmpty(apiKey)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_API_KEY")));
}
MetricsAdvisorClientBuilder builder = new MetricsAdvisorClientBuilder()
.endpoint(endpoint)
.credential(new MetricsAdvisorKeyCredential(subscriptionKey, apiKey));
this.metricsAdvisorClient = builder.buildClient();
this.metricsAdvisorAsyncClient = builder.buildAsyncClient();
this.alertConfigId = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_ALERT_CONFIG_ID");
if (CoreUtils.isNullOrEmpty(alertConfigId)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_ALERT_CONFIG_ID")));
}
this.alertId = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_ALERT_ID");
if (CoreUtils.isNullOrEmpty(alertId)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_ALERT_ID")));
}
this.detectionConfigId
= Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_DETECTION_CONFIG_ID");
if (CoreUtils.isNullOrEmpty(detectionConfigId)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_DETECTION_CONFIG_ID")));
}
this.incidentId = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_INCIDENT_ID");
if (CoreUtils.isNullOrEmpty(incidentId)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_INCIDENT_ID")));
}
this.maxListElements = Configuration.getGlobalConfiguration()
.get("METRICS_ADVISOR_MAX_LIST_ELEMENTS", DEFAULT_MAX_LIST_ELEMENTS);
} | .get("METRICS_ADVISOR_MAX_LIST_ELEMENTS", DEFAULT_MAX_LIST_ELEMENTS); | public ServiceTest(TOptions options) {
super(options);
final String endpoint = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_ENDPOINT");
if (CoreUtils.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_ENDPOINT")));
}
final String subscriptionKey = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_SUBSCRIPTION_KEY");
if (CoreUtils.isNullOrEmpty(subscriptionKey)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_SUBSCRIPTION_KEY")));
}
final String apiKey = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_API_KEY");
if (CoreUtils.isNullOrEmpty(apiKey)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_API_KEY")));
}
MetricsAdvisorClientBuilder builder = new MetricsAdvisorClientBuilder()
.endpoint(endpoint)
.credential(new MetricsAdvisorKeyCredential(subscriptionKey, apiKey));
this.metricsAdvisorClient = builder.buildClient();
this.metricsAdvisorAsyncClient = builder.buildAsyncClient();
this.alertConfigId = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_ALERT_CONFIG_ID");
if (CoreUtils.isNullOrEmpty(alertConfigId)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_ALERT_CONFIG_ID")));
}
this.alertId = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_ALERT_ID");
if (CoreUtils.isNullOrEmpty(alertId)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_ALERT_ID")));
}
this.detectionConfigId
= Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_DETECTION_CONFIG_ID");
if (CoreUtils.isNullOrEmpty(detectionConfigId)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_DETECTION_CONFIG_ID")));
}
this.incidentId = Configuration.getGlobalConfiguration().get("METRICS_ADVISOR_INCIDENT_ID");
if (CoreUtils.isNullOrEmpty(incidentId)) {
throw logger.logExceptionAsError(
new RuntimeException(String.format(CONFIGURATION_ERROR, "METRICS_ADVISOR_INCIDENT_ID")));
}
this.maxListElements = Configuration.getGlobalConfiguration()
.get("METRICS_ADVISOR_MAX_LIST_ELEMENTS", DEFAULT_MAX_LIST_ELEMENTS);
} | class ServiceTest<TOptions extends PerfStressOptions> extends PerfStressTest<TOptions> {
private static final String CONFIGURATION_ERROR = "Configuration %s must be set in either environment variables "
+ "or system properties.%n";
private static final int DEFAULT_MAX_LIST_ELEMENTS = 100;
private final ClientLogger logger = new ClientLogger(ServiceTest.class);
protected final MetricsAdvisorClient metricsAdvisorClient;
protected final MetricsAdvisorAsyncClient metricsAdvisorAsyncClient;
protected final String alertConfigId;
protected final String alertId;
protected final String detectionConfigId;
protected final String incidentId;
protected final int maxListElements;
/**
* Creates an instance of performance test.
*
* @param options the options configured for the test.
*/
} | class ServiceTest<TOptions extends PerfStressOptions> extends PerfStressTest<TOptions> {
private static final String CONFIGURATION_ERROR = "Configuration %s must be set in either environment variables "
+ "or system properties.%n";
private static final int DEFAULT_MAX_LIST_ELEMENTS = 100;
private final ClientLogger logger = new ClientLogger(ServiceTest.class);
protected final MetricsAdvisorClient metricsAdvisorClient;
protected final MetricsAdvisorAsyncClient metricsAdvisorAsyncClient;
protected final String alertConfigId;
protected final String alertId;
protected final String detectionConfigId;
protected final String incidentId;
protected final int maxListElements;
/**
* Creates an instance of performance test.
*
* @param options the options configured for the test.
*/
} |
NIT: super is not needed. | public Mono<Void> runAsync() {
return super.metricsAdvisorAsyncClient
.listIncidentRootCauses(super.detectionConfigId,
super.incidentId)
.take(super.maxListElements)
.then();
} | return super.metricsAdvisorAsyncClient | public Mono<Void> runAsync() {
return super.metricsAdvisorAsyncClient
.listIncidentRootCauses(super.detectionConfigId,
super.incidentId)
.take(super.maxListElements)
.then();
} | class RootCauseListTest extends ServiceTest<PerfStressOptions> {
/**
* Creates RootCauseTest object.
*
* @param options the configurable options for perf testing this class.
*/
public RootCauseListTest(PerfStressOptions options) {
super(options);
}
@Override
public void run() {
super.metricsAdvisorClient
.listIncidentRootCauses(super.detectionConfigId,
super.incidentId)
.stream()
.limit(super.maxListElements)
.forEach(rootCause -> {
});
}
@Override
} | class RootCauseListTest extends ServiceTest<PerfStressOptions> {
/**
* Creates RootCauseTest object.
*
* @param options the configurable options for perf testing this class.
*/
public RootCauseListTest(PerfStressOptions options) {
super(options);
}
@Override
public void run() {
super.metricsAdvisorClient
.listIncidentRootCauses(super.detectionConfigId,
super.incidentId)
.stream()
.limit(super.maxListElements)
.forEach(rootCause -> {
});
}
@Override
} |
I think this is an important log and should be logged as `warning` instead of `verbose`. | private boolean shouldRetryWithRedirect(int statusCode, int tryCount) {
if (tryCount >= MAX_REDIRECT_RETRIES) {
logger.verbose("Max redirect retries limit reached:%d.", MAX_REDIRECT_RETRIES);
return false;
}
return statusCode == HttpURLConnection.HTTP_MOVED_TEMP
|| statusCode == HttpURLConnection.HTTP_MOVED_PERM
|| statusCode == PERMANENT_REDIRECT_STATUS_CODE;
} | logger.verbose("Max redirect retries limit reached:%d.", MAX_REDIRECT_RETRIES); | private boolean shouldRetryWithRedirect(int statusCode, int tryCount) {
if (tryCount >= MAX_REDIRECT_RETRIES) {
logger.verbose("Max redirect retries limit reached:%d.", MAX_REDIRECT_RETRIES);
return false;
}
return statusCode == HttpURLConnection.HTTP_MOVED_TEMP
|| statusCode == HttpURLConnection.HTTP_MOVED_PERM
|| statusCode == PERMANENT_REDIRECT_STATUS_CODE;
} | class AzureMonitorRedirectPolicy implements HttpPipelinePolicy {
private static final int PERMANENT_REDIRECT_STATUS_CODE = 308;
private static final int MAX_REDIRECT_RETRIES = 10;
private final ClientLogger logger = new ClientLogger(AzureMonitorRedirectPolicy.class);
private String redirectedEndpointUrl;
@Override
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
return attemptRetry(context, next, context.getHttpRequest(), 0);
}
/**
* Function to process through the HTTP Response received in the pipeline
* and retry sending the request with new redirect url.
*/
private Mono<HttpResponse> attemptRetry(final HttpPipelineCallContext context,
final HttpPipelineNextPolicy next,
final HttpRequest originalHttpRequest,
final int retryCount) {
context.setHttpRequest(originalHttpRequest.copy());
if (this.redirectedEndpointUrl != null) {
context.getHttpRequest().setUrl(this.redirectedEndpointUrl);
}
return next.clone().process()
.flatMap(httpResponse -> {
if (shouldRetryWithRedirect(httpResponse.getStatusCode(), retryCount)) {
String responseLocation = httpResponse.getHeaderValue("Location");
if (responseLocation != null) {
this.redirectedEndpointUrl = responseLocation;
return attemptRetry(context, next, originalHttpRequest, retryCount + 1);
}
}
return Mono.just(httpResponse);
});
}
/**
* Determines if it's a valid retry scenario based on statusCode and tryCount.
*
* @param statusCode HTTP response status code
* @param tryCount Redirect retries so far
* @return True if statusCode corresponds to HTTP redirect response codes and redirect
* retries is less than {@code MAX_REDIRECT_RETRIES}.
*/
} | class AzureMonitorRedirectPolicy implements HttpPipelinePolicy {
private static final int PERMANENT_REDIRECT_STATUS_CODE = 308;
private static final int MAX_REDIRECT_RETRIES = 10;
private final ClientLogger logger = new ClientLogger(AzureMonitorRedirectPolicy.class);
private String redirectedEndpointUrl;
@Override
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
return attemptRetry(context, next, context.getHttpRequest(), 0);
}
/**
* Function to process through the HTTP Response received in the pipeline
* and retry sending the request with new redirect url.
*/
private Mono<HttpResponse> attemptRetry(final HttpPipelineCallContext context,
final HttpPipelineNextPolicy next,
final HttpRequest originalHttpRequest,
final int retryCount) {
context.setHttpRequest(originalHttpRequest.copy());
if (this.redirectedEndpointUrl != null) {
context.getHttpRequest().setUrl(this.redirectedEndpointUrl);
}
return next.clone().process()
.flatMap(httpResponse -> {
if (shouldRetryWithRedirect(httpResponse.getStatusCode(), retryCount)) {
String responseLocation = httpResponse.getHeaderValue("Location");
if (responseLocation != null) {
this.redirectedEndpointUrl = responseLocation;
return attemptRetry(context, next, originalHttpRequest, retryCount + 1);
}
}
return Mono.just(httpResponse);
});
}
/**
* Determines if it's a valid retry scenario based on statusCode and tryCount.
*
* @param statusCode HTTP response status code
* @param tryCount Redirect retries so far
* @return True if statusCode corresponds to HTTP redirect response codes and redirect
* retries is less than {@code MAX_REDIRECT_RETRIES}.
*/
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.