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
No, this was not GA'd
public Mono<ShareInfo> setProperties(ShareSetPropertiesOptions options) { try { return setPropertiesWithResponse(options).map(Response::getValue); } catch (RuntimeException ex) { return monoError(logger, ex); } }
} catch (RuntimeException ex) {
public Mono<ShareInfo> setProperties(ShareSetPropertiesOptions options) { try { return setPropertiesWithResponse(options).map(Response::getValue); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ShareAsyncClient { private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class); private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String snapshot; private final String accountName; private final ShareServiceVersion serviceVersion; /** * Creates a ShareAsyncClient that sends requests to the storage share at {@link AzureFileStorageImpl * endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the * {@code azureFileStorageClient}. * * @param client Client that interacts with the service interfaces * @param shareName Name of the share */ ShareAsyncClient(AzureFileStorageImpl client, String shareName, String snapshot, String accountName, ShareServiceVersion serviceVersion) { Objects.requireNonNull(shareName, "'shareName' cannot be null."); this.shareName = shareName; this.snapshot = snapshot; this.accountName = accountName; this.azureFileStorageClient = client; this.serviceVersion = serviceVersion; } /** * Get the url of the storage share client. * * @return the url of the Storage Share. */ public String getShareUrl() { StringBuilder shareUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/").append(shareName); if (snapshot != null) { shareUrlString.append("?sharesnapshot=").append(snapshot); } return shareUrlString.toString(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public ShareServiceVersion getServiceVersion() { return serviceVersion; } /** * Constructs a {@link ShareDirectoryAsyncClient} that interacts with the root directory in the share. * * <p>If the directory doesn't exist in the share {@link ShareDirectoryAsyncClient * azureFileStorageClient will need to be called before interaction with the directory can happen.</p> * * @return a {@link ShareDirectoryAsyncClient} that interacts with the root directory in the share */ public ShareDirectoryAsyncClient getRootDirectoryClient() { return getDirectoryClient(""); } /** * Constructs a {@link ShareDirectoryAsyncClient} that interacts with the specified directory. * * <p>If the directory doesn't exist in the share {@link ShareDirectoryAsyncClient * azureFileStorageClient will need to be called before interaction with the directory can happen.</p> * * @param directoryName Name of the directory * @return a {@link ShareDirectoryAsyncClient} that interacts with the directory in the share */ public ShareDirectoryAsyncClient getDirectoryClient(String directoryName) { return new ShareDirectoryAsyncClient(azureFileStorageClient, shareName, directoryName, snapshot, accountName, serviceVersion); } /** * Constructs a {@link ShareFileAsyncClient} that interacts with the specified file. * * <p>If the file doesn't exist in the share {@link ShareFileAsyncClient
class ShareAsyncClient { private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class); private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String snapshot; private final String accountName; private final ShareServiceVersion serviceVersion; /** * Creates a ShareAsyncClient that sends requests to the storage share at {@link AzureFileStorageImpl * endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the * {@code azureFileStorageClient}. * * @param client Client that interacts with the service interfaces * @param shareName Name of the share */ ShareAsyncClient(AzureFileStorageImpl client, String shareName, String snapshot, String accountName, ShareServiceVersion serviceVersion) { Objects.requireNonNull(shareName, "'shareName' cannot be null."); this.shareName = shareName; this.snapshot = snapshot; this.accountName = accountName; this.azureFileStorageClient = client; this.serviceVersion = serviceVersion; } /** * Get the url of the storage share client. * * @return the url of the Storage Share. */ public String getShareUrl() { StringBuilder shareUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/").append(shareName); if (snapshot != null) { shareUrlString.append("?sharesnapshot=").append(snapshot); } return shareUrlString.toString(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public ShareServiceVersion getServiceVersion() { return serviceVersion; } /** * Constructs a {@link ShareDirectoryAsyncClient} that interacts with the root directory in the share. * * <p>If the directory doesn't exist in the share {@link ShareDirectoryAsyncClient * azureFileStorageClient will need to be called before interaction with the directory can happen.</p> * * @return a {@link ShareDirectoryAsyncClient} that interacts with the root directory in the share */ public ShareDirectoryAsyncClient getRootDirectoryClient() { return getDirectoryClient(""); } /** * Constructs a {@link ShareDirectoryAsyncClient} that interacts with the specified directory. * * <p>If the directory doesn't exist in the share {@link ShareDirectoryAsyncClient * azureFileStorageClient will need to be called before interaction with the directory can happen.</p> * * @param directoryName Name of the directory * @return a {@link ShareDirectoryAsyncClient} that interacts with the directory in the share */ public ShareDirectoryAsyncClient getDirectoryClient(String directoryName) { return new ShareDirectoryAsyncClient(azureFileStorageClient, shareName, directoryName, snapshot, accountName, serviceVersion); } /** * Constructs a {@link ShareFileAsyncClient} that interacts with the specified file. * * <p>If the file doesn't exist in the share {@link ShareFileAsyncClient
List models?
public void relationshipListOperationWithMultiplePages(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) { DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion); String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); List<String> createdOutgoingRelationshipIds = new ArrayList<>(); List<String> createdIncomingRelationshipIds = new ArrayList<>(); try { createModelsAndTwins(asyncClient, floorModelId, roomModelId, hvacModelId, floorTwinId, roomTwinId, hvacTwinId); String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true); String roomContainedInFloorPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP); for (int i = 0; i < BULK_RELATIONSHIP_COUNT; i++) { String relationshipId = FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID + this.testResourceNamer.randomUuid(); StepVerifier.create( asyncClient.createRelationship( floorTwinId, relationshipId, deserializeJsonString(floorContainsRoomPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext(response -> logger.info("Created relationship with Id {}", relationshipId)) .verifyComplete(); createdOutgoingRelationshipIds.add(relationshipId); } for (int i = 0; i < BULK_RELATIONSHIP_COUNT; i++) { String relationshipId = ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID + this.testResourceNamer.randomUuid(); StepVerifier.create( asyncClient.createRelationship( roomTwinId, relationshipId, deserializeJsonString(roomContainedInFloorPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext(response -> logger.info("Created relationship with Id {}", relationshipId)) .verifyComplete(); createdIncomingRelationshipIds.add(relationshipId); } AtomicInteger outgoingRelationshipsPageCount = new AtomicInteger(); StepVerifier.create(asyncClient.listRelationships(floorTwinId, BasicRelationship.class).byPage()) .thenConsumeWhile( page -> { outgoingRelationshipsPageCount.getAndIncrement(); logger.info("content for this page " + outgoingRelationshipsPageCount); for (BasicRelationship relationship : page.getValue()) { logger.info(relationship.getId()); } if (page.getContinuationToken() != null) { assertEquals(RELATIONSHIP_PAGE_SIZE_DEFAULT, page.getValue().size(), "Unexpected page size for a non-terminal page"); } return true; }) .verifyComplete(); assertThat(outgoingRelationshipsPageCount.get()).isGreaterThan(1); AtomicInteger incomingRelationshipsPageCount = new AtomicInteger(); StepVerifier.create(asyncClient.listIncomingRelationships(floorTwinId, null).byPage()) .thenConsumeWhile( page -> { incomingRelationshipsPageCount.getAndIncrement(); logger.info("content for this page " + incomingRelationshipsPageCount); for (IncomingRelationship relationship : page.getValue()) { logger.info(relationship.getSourceId()); } if (page.getContinuationToken() != null) { assertEquals(RELATIONSHIP_PAGE_SIZE_DEFAULT, page.getValue().size(), "Unexpected page size for a non-terminal page"); } return true; }) .verifyComplete(); assertThat(incomingRelationshipsPageCount.get()).isGreaterThan(1); } catch (Exception ex) { fail("Test run failed", ex); } finally { try { logger.info("Cleaning up test resources."); logger.info("Deleting created relationships."); createdOutgoingRelationshipIds.forEach(relationshipId -> asyncClient.deleteRelationship(floorTwinId, relationshipId).block()); createdIncomingRelationshipIds.forEach(relationshipId -> asyncClient.deleteRelationship(roomTwinId, relationshipId).block()); logger.info("Deleting created digital twins."); asyncClient.deleteDigitalTwin(floorTwinId).block(); asyncClient.deleteDigitalTwin(roomTwinId).block(); asyncClient.deleteDigitalTwin(hvacTwinId).block(); logger.info("Deleting created models."); asyncClient.deleteModel(floorModelId).block(); asyncClient.deleteModel(roomModelId).block(); asyncClient.deleteModel(hvacModelId).block(); } catch (Exception ex) { fail("Test cleanup failed", ex); } } }
public void relationshipListOperationWithMultiplePages(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) { DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion); String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); List<String> createdOutgoingRelationshipIds = new ArrayList<>(); List<String> createdIncomingRelationshipIds = new ArrayList<>(); try { createModelsAndTwins(asyncClient, floorModelId, roomModelId, hvacModelId, floorTwinId, roomTwinId, hvacTwinId); String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true); String roomContainedInFloorPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP); for (int i = 0; i < BULK_RELATIONSHIP_COUNT; i++) { String relationshipId = FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID + this.testResourceNamer.randomUuid(); StepVerifier.create( asyncClient.createRelationship( floorTwinId, relationshipId, deserializeJsonString(floorContainsRoomPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext(response -> logger.info("Created relationship with Id {}", relationshipId)) .verifyComplete(); createdOutgoingRelationshipIds.add(relationshipId); } for (int i = 0; i < BULK_RELATIONSHIP_COUNT; i++) { String relationshipId = ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID + this.testResourceNamer.randomUuid(); StepVerifier.create( asyncClient.createRelationship( roomTwinId, relationshipId, deserializeJsonString(roomContainedInFloorPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext(response -> logger.info("Created relationship with Id {}", relationshipId)) .verifyComplete(); createdIncomingRelationshipIds.add(relationshipId); } AtomicInteger outgoingRelationshipsPageCount = new AtomicInteger(); StepVerifier.create(asyncClient.listRelationships(floorTwinId, BasicRelationship.class).byPage()) .thenConsumeWhile( page -> { outgoingRelationshipsPageCount.getAndIncrement(); logger.info("content for this page " + outgoingRelationshipsPageCount); for (BasicRelationship relationship : page.getValue()) { logger.info(relationship.getId()); } if (page.getContinuationToken() != null) { assertEquals(RELATIONSHIP_PAGE_SIZE_DEFAULT, page.getValue().size(), "Unexpected page size for a non-terminal page"); } return true; }) .verifyComplete(); assertThat(outgoingRelationshipsPageCount.get()).isGreaterThan(1); AtomicInteger incomingRelationshipsPageCount = new AtomicInteger(); StepVerifier.create(asyncClient.listIncomingRelationships(floorTwinId, null).byPage()) .thenConsumeWhile( page -> { incomingRelationshipsPageCount.getAndIncrement(); logger.info("content for this page " + incomingRelationshipsPageCount); for (IncomingRelationship relationship : page.getValue()) { logger.info(relationship.getSourceId()); } if (page.getContinuationToken() != null) { assertEquals(RELATIONSHIP_PAGE_SIZE_DEFAULT, page.getValue().size(), "Unexpected page size for a non-terminal page"); } return true; }) .verifyComplete(); assertThat(incomingRelationshipsPageCount.get()).isGreaterThan(1); } catch (Exception ex) { fail("Test run failed", ex); } finally { try { logger.info("Cleaning up test resources."); logger.info("Deleting created relationships."); createdOutgoingRelationshipIds.forEach(relationshipId -> asyncClient.deleteRelationship(floorTwinId, relationshipId).block()); createdIncomingRelationshipIds.forEach(relationshipId -> asyncClient.deleteRelationship(roomTwinId, relationshipId).block()); logger.info("Deleting created digital twins."); asyncClient.deleteDigitalTwin(floorTwinId).block(); asyncClient.deleteDigitalTwin(roomTwinId).block(); asyncClient.deleteDigitalTwin(hvacTwinId).block(); logger.info("Deleting created models."); asyncClient.deleteModel(floorModelId).block(); asyncClient.deleteModel(roomModelId).block(); asyncClient.deleteModel(hvacModelId).block(); } catch (Exception ex) { fail("Test cleanup failed", ex); } } }
class DigitalTwinsRelationshipAsyncTest extends DigitalTwinsRelationshipTestBase { private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipAsyncTest.class); @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.digitaltwins.core.TestHelper @Override public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) throws JsonProcessingException { DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion); String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); try { createModelsAndTwins(asyncClient, floorModelId, roomModelId, hvacModelId, floorTwinId, roomTwinId, hvacTwinId); String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true); String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP); String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP); String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP); List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false); StepVerifier .create(asyncClient.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, deserializeJsonString(floorContainsRoomPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext( basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID) .as("Created relationship from floor -> room"); logger.info("Created {} relationship between source = {} and target = {}", basicRelationship.getId(), basicRelationship.getSourceId(), basicRelationship.getTargetId()); } ) .verifyComplete(); StepVerifier .create(asyncClient.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, deserializeJsonString(floorCooledByHvacPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext( basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID) .as("Created relationship from floor -> hvac"); logger.info("Created {} relationship between source = {} and target = {}", basicRelationship.getId(), basicRelationship.getSourceId(), basicRelationship.getTargetId()); } ) .verifyComplete(); StepVerifier .create(asyncClient.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, deserializeJsonString(floorTwinCoolsRelationshipPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext( basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID) .as("Created relationship from hvac -> floor"); logger.info("Created {} relationship between source = {} and target = {}", basicRelationship.getId(), basicRelationship.getSourceId(), basicRelationship.getTargetId()); } ) .verifyComplete(); StepVerifier .create(asyncClient.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, deserializeJsonString(floorTwinContainedInRelationshipPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext( basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID) .as("Created relationship from room -> floor"); logger.info("Created {} relationship between source = {} and target = {}", basicRelationship.getId(), basicRelationship.getSourceId(), basicRelationship.getTargetId()); } ) .verifyComplete(); StepVerifier.create(asyncClient.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, String.class)) .verifyErrorSatisfies(ex -> assertRestException(ex, HTTP_PRECON_FAILED)); StepVerifier .create(asyncClient.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null)) .assertNext( voidDigitalTwinsResponse -> { assertThat(voidDigitalTwinsResponse.getStatusCode()) .as("Updated relationship floor -> room") .isEqualTo(HTTP_NO_CONTENT); logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId); } ) .verifyComplete(); StepVerifier .create(asyncClient.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class)) .assertNext(basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID) .as("Retrieved floor -> room relationship"); logger.info("Retrieved {} relationship under source {}", basicRelationship.getId(), basicRelationship.getSourceId()); }) .verifyComplete(); List<String> incomingRelationshipsSourceIds = new ArrayList<>(); StepVerifier .create(asyncClient.listIncomingRelationships(floorTwinId, null)) .assertNext(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId())) .assertNext(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId())) .expectComplete() .verify(); assertThat(incomingRelationshipsSourceIds) .as("Floor has incoming relationships from room and hvac") .containsExactlyInAnyOrder(roomTwinId, hvacTwinId); logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray())); List<String> relationshipsTargetIds = new ArrayList<>(); StepVerifier .create(asyncClient.listRelationships(floorTwinId, BasicRelationship.class)) .assertNext(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId())) .assertNext(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId())) .expectComplete() .verify(); assertThat(relationshipsTargetIds) .as("Floor has a relationship to room and hvac") .containsExactlyInAnyOrder(roomTwinId, hvacTwinId); logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray())); StepVerifier .create(asyncClient.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, null)) .assertNext(basicRelationship -> { assertThat(basicRelationship.getName()) .isEqualTo(CONTAINED_IN_RELATIONSHIP) .as("Room has only one containedIn relationship to floor"); assertThat(basicRelationship.getTargetId()) .isEqualTo(floorTwinId) .as("Room has only one containedIn relationship to floor"); logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId); }) .expectComplete() .verify(); StepVerifier .create(asyncClient.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)) .verifyComplete(); logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId); StepVerifier .create(asyncClient.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)) .verifyComplete(); logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId); StepVerifier .create(asyncClient.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)) .verifyComplete(); logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId); StepVerifier .create(asyncClient.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID)) .verifyComplete(); logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId); StepVerifier .create(asyncClient.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, String.class)) .verifyErrorSatisfies(ex -> assertRestException(ex, HTTP_NOT_FOUND)); } finally { try { logger.info("Cleaning up test resources."); logger.info("Deleting created relationships."); List<BasicRelationship> relationships = new ArrayList<>(); asyncClient.listRelationships(floorTwinId, BasicRelationship.class) .doOnNext(relationships::add) .blockLast(); asyncClient.listRelationships(roomTwinId, BasicRelationship.class) .doOnNext(relationships::add) .blockLast(); asyncClient.listRelationships(hvacTwinId, BasicRelationship.class) .doOnNext(relationships::add) .blockLast(); relationships.forEach(basicRelationship -> asyncClient.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()).block()); logger.info("Deleting created digital twins."); asyncClient.deleteDigitalTwin(floorTwinId).block(); asyncClient.deleteDigitalTwin(roomTwinId).block(); asyncClient.deleteDigitalTwin(hvacTwinId).block(); logger.info("Deleting created models."); asyncClient.deleteModel(floorModelId).block(); asyncClient.deleteModel(roomModelId).block(); asyncClient.deleteModel(hvacModelId).block(); } catch (Exception ex) { fail("Test cleanup failed", ex); } } } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.digitaltwins.core.TestHelper @Override private void createModelsAndTwins(DigitalTwinsAsyncClient asyncClient, String floorModelId, String roomModelId, String hvacModelId, String floorTwinId, String roomTwinId, String hvacTwinId) throws JsonProcessingException { createModelsRunner( floorModelId, roomModelId, hvacModelId, modelsList -> StepVerifier .create(asyncClient.createModels(modelsList)) .assertNext(createResponseList -> logger.info("Created models successfully")) .verifyComplete()); createFloorTwinRunner( floorTwinId, floorModelId, (twinId, twin) -> StepVerifier .create(asyncClient.createDigitalTwin(twinId, twin, BasicDigitalTwin.class)) .assertNext(basicDigitalTwin -> logger.info("Created {} twin successfully", basicDigitalTwin.getId())) .verifyComplete()); createRoomTwinRunner( roomTwinId, roomModelId, (twinId, twin) -> StepVerifier .create(asyncClient.createDigitalTwin(twinId, twin, BasicDigitalTwin.class)) .assertNext(basicDigitalTwin -> logger.info("Created {} twin successfully", basicDigitalTwin.getId())) .verifyComplete()); createHvacTwinRunner( hvacTwinId, hvacModelId, (twinId, twin) -> StepVerifier .create(asyncClient.createDigitalTwin(twinId, twin, BasicDigitalTwin.class)) .assertNext(basicDigitalTwin -> logger.info("Created {} twin successfully", basicDigitalTwin.getId())) .verifyComplete()); } }
class DigitalTwinsRelationshipAsyncTest extends DigitalTwinsRelationshipTestBase { private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipAsyncTest.class); @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.digitaltwins.core.TestHelper @Override public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) throws JsonProcessingException { DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion); String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator); try { createModelsAndTwins(asyncClient, floorModelId, roomModelId, hvacModelId, floorTwinId, roomTwinId, hvacTwinId); String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true); String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP); String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP); String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP); List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false); StepVerifier .create(asyncClient.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, deserializeJsonString(floorContainsRoomPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext( basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID) .as("Created relationship from floor -> room"); logger.info("Created {} relationship between source = {} and target = {}", basicRelationship.getId(), basicRelationship.getSourceId(), basicRelationship.getTargetId()); } ) .verifyComplete(); StepVerifier .create(asyncClient.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, deserializeJsonString(floorCooledByHvacPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext( basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID) .as("Created relationship from floor -> hvac"); logger.info("Created {} relationship between source = {} and target = {}", basicRelationship.getId(), basicRelationship.getSourceId(), basicRelationship.getTargetId()); } ) .verifyComplete(); StepVerifier .create(asyncClient.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, deserializeJsonString(floorTwinCoolsRelationshipPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext( basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID) .as("Created relationship from hvac -> floor"); logger.info("Created {} relationship between source = {} and target = {}", basicRelationship.getId(), basicRelationship.getSourceId(), basicRelationship.getTargetId()); } ) .verifyComplete(); StepVerifier .create(asyncClient.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, deserializeJsonString(floorTwinContainedInRelationshipPayload, BasicRelationship.class), BasicRelationship.class)) .assertNext( basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID) .as("Created relationship from room -> floor"); logger.info("Created {} relationship between source = {} and target = {}", basicRelationship.getId(), basicRelationship.getSourceId(), basicRelationship.getTargetId()); } ) .verifyComplete(); StepVerifier.create(asyncClient.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, String.class)) .verifyErrorSatisfies(ex -> assertRestException(ex, HTTP_PRECON_FAILED)); StepVerifier .create(asyncClient.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null)) .assertNext( voidDigitalTwinsResponse -> { assertThat(voidDigitalTwinsResponse.getStatusCode()) .as("Updated relationship floor -> room") .isEqualTo(HTTP_NO_CONTENT); logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId); } ) .verifyComplete(); StepVerifier .create(asyncClient.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class)) .assertNext(basicRelationship -> { assertThat(basicRelationship.getId()) .isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID) .as("Retrieved floor -> room relationship"); logger.info("Retrieved {} relationship under source {}", basicRelationship.getId(), basicRelationship.getSourceId()); }) .verifyComplete(); List<String> incomingRelationshipsSourceIds = new ArrayList<>(); StepVerifier .create(asyncClient.listIncomingRelationships(floorTwinId, null)) .assertNext(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId())) .assertNext(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId())) .expectComplete() .verify(); assertThat(incomingRelationshipsSourceIds) .as("Floor has incoming relationships from room and hvac") .containsExactlyInAnyOrder(roomTwinId, hvacTwinId); logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray())); List<String> relationshipsTargetIds = new ArrayList<>(); StepVerifier .create(asyncClient.listRelationships(floorTwinId, BasicRelationship.class)) .assertNext(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId())) .assertNext(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId())) .expectComplete() .verify(); assertThat(relationshipsTargetIds) .as("Floor has a relationship to room and hvac") .containsExactlyInAnyOrder(roomTwinId, hvacTwinId); logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray())); StepVerifier .create(asyncClient.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, null)) .assertNext(basicRelationship -> { assertThat(basicRelationship.getName()) .isEqualTo(CONTAINED_IN_RELATIONSHIP) .as("Room has only one containedIn relationship to floor"); assertThat(basicRelationship.getTargetId()) .isEqualTo(floorTwinId) .as("Room has only one containedIn relationship to floor"); logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId); }) .expectComplete() .verify(); StepVerifier .create(asyncClient.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)) .verifyComplete(); logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId); StepVerifier .create(asyncClient.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)) .verifyComplete(); logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId); StepVerifier .create(asyncClient.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)) .verifyComplete(); logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId); StepVerifier .create(asyncClient.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID)) .verifyComplete(); logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId); StepVerifier .create(asyncClient.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, String.class)) .verifyErrorSatisfies(ex -> assertRestException(ex, HTTP_NOT_FOUND)); } finally { try { logger.info("Cleaning up test resources."); logger.info("Deleting created relationships."); List<BasicRelationship> relationships = new ArrayList<>(); asyncClient.listRelationships(floorTwinId, BasicRelationship.class) .doOnNext(relationships::add) .blockLast(); asyncClient.listRelationships(roomTwinId, BasicRelationship.class) .doOnNext(relationships::add) .blockLast(); asyncClient.listRelationships(hvacTwinId, BasicRelationship.class) .doOnNext(relationships::add) .blockLast(); relationships.forEach(basicRelationship -> asyncClient.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()).block()); logger.info("Deleting created digital twins."); asyncClient.deleteDigitalTwin(floorTwinId).block(); asyncClient.deleteDigitalTwin(roomTwinId).block(); asyncClient.deleteDigitalTwin(hvacTwinId).block(); logger.info("Deleting created models."); asyncClient.deleteModel(floorModelId).block(); asyncClient.deleteModel(roomModelId).block(); asyncClient.deleteModel(hvacModelId).block(); } catch (Exception ex) { fail("Test cleanup failed", ex); } } } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.digitaltwins.core.TestHelper @Override private void createModelsAndTwins(DigitalTwinsAsyncClient asyncClient, String floorModelId, String roomModelId, String hvacModelId, String floorTwinId, String roomTwinId, String hvacTwinId) throws JsonProcessingException { createModelsRunner( floorModelId, roomModelId, hvacModelId, modelsList -> StepVerifier .create(asyncClient.createModels(modelsList)) .assertNext(createResponseList -> logger.info("Created models successfully")) .verifyComplete()); createFloorTwinRunner( floorTwinId, floorModelId, (twinId, twin) -> StepVerifier .create(asyncClient.createDigitalTwin(twinId, twin, BasicDigitalTwin.class)) .assertNext(basicDigitalTwin -> logger.info("Created {} twin successfully", basicDigitalTwin.getId())) .verifyComplete()); createRoomTwinRunner( roomTwinId, roomModelId, (twinId, twin) -> StepVerifier .create(asyncClient.createDigitalTwin(twinId, twin, BasicDigitalTwin.class)) .assertNext(basicDigitalTwin -> logger.info("Created {} twin successfully", basicDigitalTwin.getId())) .verifyComplete()); createHvacTwinRunner( hvacTwinId, hvacModelId, (twinId, twin) -> StepVerifier .create(asyncClient.createDigitalTwin(twinId, twin, BasicDigitalTwin.class)) .assertNext(basicDigitalTwin -> logger.info("Created {} twin successfully", basicDigitalTwin.getId())) .verifyComplete()); } }
@JonathanGiles, @srnagar, I'd like to see us create a guideline around the default serializer to be used when one isn't passed. In some locations we use `JsonSerializer`/`ObjectSerializer` and in others we default to using `JacksonAdapter`. I have a feeling we may need to go down the route of always falling back to `JacksonAdapter`, except with serialization formats we didn't previously support such as Avro and Protobuf, as using `JsonSerializerProviders.createInstance` may result in customer applications throwing an exception when they previously didn't. This restriction may only apply to logic in `azure-core` which could accept an `ObjectSerializer`/`JsonSerializer` as it cannot take a dependency on the implementation libraries.
public static BinaryData fromObject(Object data) { Objects.requireNonNull(data, "'data' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonSerializerProviders.createInstance().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
JsonSerializerProviders.createInstance().serialize(outputStream, data);
public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private final byte[] data; /** * Create instance of {@link BinaryData} given the data. * @param data to represent as bytes. * @throws NullPointerException If {@code data} is null. */ BinaryData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = Arrays.copyOf(data, data.length); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /** * Provides {@link Mono} of {@link InputStream} for the data represented by this {@link BinaryData} object. * * @return {@link InputStream} representation of the {@link BinaryData}. */ public Mono<InputStream> toStreamAsync() { return Mono.fromCallable(() -> toStream()); } /** * Create {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} is * not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return fromBytes(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously create {@link BinaryData} instance with given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. * * @param inputStream to read bytes from. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Create {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return monoError(LOGGER, new NullPointerException("'data' cannot be null.")); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(fromBytes(bytes))); } /** * Create {@link BinaryData} instance with given data and character set. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @param charSet to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromString(String data, Charset charSet) { Objects.requireNonNull(data, "'data' cannot be null."); return new BinaryData(data.getBytes(charSet)); } /** * Create {@link BinaryData} instance with given data. The {@link String} is converted into bytes using * {@link StandardCharsets * * @param data to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { Objects.requireNonNull(data, "'data' cannot be null."); return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Create {@link BinaryData} instance with given byte array data. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(data); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link JsonSerializer}. This will * require the client to configure Json serializer in classpath. * * @param data The {@link Object} which needs to be serialized into bytes. * @throws NullPointerException if {@code data} is null. * @throws IllegalStateException If cannot find any JSON serializer provider on the classpath. * @return {@link BinaryData} representing binary data. Or {@code null} if it fails to serialize the data. * * @see JsonSerializer */ /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code inputStream} or {@code serializer} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { Objects.requireNonNull(data, "'data' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code inputStream} or {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { Objects.requireNonNull(data, "'data' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using {@link StandardCharsets * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Provides {@link String} representation of this {@link BinaryData} object given a character set. * * @param charSet to use to convert bytes into {@link String}. * @return {@link String} representation of the the binary data. */ public String toString(Charset charSet) { return new String(this.data, charSet); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the provided * {@link ObjectSerializer} on the {@link BinaryData}. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException if {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { return Mono.fromCallable(() -> toObject(clazz, serializer)); } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]); private static final Object LOCK = new Object(); private final byte[] data; private static volatile JsonSerializer defaultJsonSerializer; /** * Create an instance of {@link BinaryData} from the given data. * * @param data to represent as bytes. */ BinaryData(byte[] data) { this.data = data; } /** * Creates a {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} * is not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { if (Objects.isNull(inputStream)) { return EMPTY_DATA; } final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } dataOutputBuffer.flush(); return new BinaryData(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously creates a {@link BinaryData} instance with the given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. If the {@link InputStream} is {@code null}, an empty * {@link BinaryData} will be returned. * * @param inputStream to read bytes from. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates a {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. If the {@link Flux} is {@code null}, an * empty {@link BinaryData} will be returned. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return Mono.just(EMPTY_DATA); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(new BinaryData(bytes))); } /** * Creates a {@link BinaryData} instance with given data. The {@link String} is converted into bytes using UTF_8 * character set. If the String is {@code null}, an empty {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { if (Objects.isNull(data) || data.length() == 0) { return EMPTY_DATA; } return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Creates a {@link BinaryData} instance with given byte array data. If the byte array is {@code null}, an empty * {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { if (Objects.isNull(data) || data.length == 0) { return EMPTY_DATA; } return new BinaryData(Arrays.copyOf(data, data.length)); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available on classpath. * The serializer on classpath must implement {@link JsonSerializer} interface. If the given Object is {@code null}, * an empty {@link BinaryData} will be returned. * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from.default.serializer * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing the JSON serialized object. * * @see JsonSerializer * @see <a href="ObjectSerializer" target="_blank">More about serialization</a> */ /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If the Object is {@code null}, an empty {@link BinaryData} will be returned. * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Create an instance from Object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link BinaryData} representing binary data. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return EMPTY_DATA; } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. * @see ObjectSerializer * @see <a href="https: */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using the UTF-8 character set. * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code serializer} or {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the * provided {@link ObjectSerializer} on the {@link BinaryData}. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by using json serializer which is available in * classpath. The serializer must implement {@link JsonSerializer} interface. A singleton instance of * {@link JsonSerializer} is kept for this class to use. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return getDefaultSerializer().deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz)); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */ private static JsonSerializer getDefaultSerializer() { if (defaultJsonSerializer == null) { synchronized (LOCK) { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } } return defaultJsonSerializer; } }
Possible guidance: If `azure-core` or retrofitting a library, either we cannot accept a null serializer type or we default to `JacksonAdapter`. Reasoning is that we may introduce exceptions into a customer's application that weren't previously being thrown. If a new library, leverage `JsonSerializerProviders.createInstance()`, and other serializer providers that come in the future, as the default and include a dependency for the default implementation. Reasoning is that it is a new library and should adhere to the best practices for allowing customer configuration of serialization.
public static BinaryData fromObject(Object data) { Objects.requireNonNull(data, "'data' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonSerializerProviders.createInstance().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
JsonSerializerProviders.createInstance().serialize(outputStream, data);
public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private final byte[] data; /** * Create instance of {@link BinaryData} given the data. * @param data to represent as bytes. * @throws NullPointerException If {@code data} is null. */ BinaryData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = Arrays.copyOf(data, data.length); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /** * Provides {@link Mono} of {@link InputStream} for the data represented by this {@link BinaryData} object. * * @return {@link InputStream} representation of the {@link BinaryData}. */ public Mono<InputStream> toStreamAsync() { return Mono.fromCallable(() -> toStream()); } /** * Create {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} is * not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return fromBytes(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously create {@link BinaryData} instance with given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. * * @param inputStream to read bytes from. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Create {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return monoError(LOGGER, new NullPointerException("'data' cannot be null.")); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(fromBytes(bytes))); } /** * Create {@link BinaryData} instance with given data and character set. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @param charSet to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromString(String data, Charset charSet) { Objects.requireNonNull(data, "'data' cannot be null."); return new BinaryData(data.getBytes(charSet)); } /** * Create {@link BinaryData} instance with given data. The {@link String} is converted into bytes using * {@link StandardCharsets * * @param data to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { Objects.requireNonNull(data, "'data' cannot be null."); return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Create {@link BinaryData} instance with given byte array data. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(data); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link JsonSerializer}. This will * require the client to configure Json serializer in classpath. * * @param data The {@link Object} which needs to be serialized into bytes. * @throws NullPointerException if {@code data} is null. * @throws IllegalStateException If cannot find any JSON serializer provider on the classpath. * @return {@link BinaryData} representing binary data. Or {@code null} if it fails to serialize the data. * * @see JsonSerializer */ /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code inputStream} or {@code serializer} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { Objects.requireNonNull(data, "'data' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code inputStream} or {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { Objects.requireNonNull(data, "'data' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using {@link StandardCharsets * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Provides {@link String} representation of this {@link BinaryData} object given a character set. * * @param charSet to use to convert bytes into {@link String}. * @return {@link String} representation of the the binary data. */ public String toString(Charset charSet) { return new String(this.data, charSet); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the provided * {@link ObjectSerializer} on the {@link BinaryData}. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException if {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { return Mono.fromCallable(() -> toObject(clazz, serializer)); } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]); private static final Object LOCK = new Object(); private final byte[] data; private static volatile JsonSerializer defaultJsonSerializer; /** * Create an instance of {@link BinaryData} from the given data. * * @param data to represent as bytes. */ BinaryData(byte[] data) { this.data = data; } /** * Creates a {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} * is not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { if (Objects.isNull(inputStream)) { return EMPTY_DATA; } final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } dataOutputBuffer.flush(); return new BinaryData(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously creates a {@link BinaryData} instance with the given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. If the {@link InputStream} is {@code null}, an empty * {@link BinaryData} will be returned. * * @param inputStream to read bytes from. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates a {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. If the {@link Flux} is {@code null}, an * empty {@link BinaryData} will be returned. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return Mono.just(EMPTY_DATA); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(new BinaryData(bytes))); } /** * Creates a {@link BinaryData} instance with given data. The {@link String} is converted into bytes using UTF_8 * character set. If the String is {@code null}, an empty {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { if (Objects.isNull(data) || data.length() == 0) { return EMPTY_DATA; } return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Creates a {@link BinaryData} instance with given byte array data. If the byte array is {@code null}, an empty * {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { if (Objects.isNull(data) || data.length == 0) { return EMPTY_DATA; } return new BinaryData(Arrays.copyOf(data, data.length)); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available on classpath. * The serializer on classpath must implement {@link JsonSerializer} interface. If the given Object is {@code null}, * an empty {@link BinaryData} will be returned. * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from.default.serializer * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing the JSON serialized object. * * @see JsonSerializer * @see <a href="ObjectSerializer" target="_blank">More about serialization</a> */ /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If the Object is {@code null}, an empty {@link BinaryData} will be returned. * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Create an instance from Object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link BinaryData} representing binary data. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return EMPTY_DATA; } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. * @see ObjectSerializer * @see <a href="https: */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using the UTF-8 character set. * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code serializer} or {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the * provided {@link ObjectSerializer} on the {@link BinaryData}. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by using json serializer which is available in * classpath. The serializer must implement {@link JsonSerializer} interface. A singleton instance of * {@link JsonSerializer} is kept for this class to use. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return getDefaultSerializer().deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz)); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */ private static JsonSerializer getDefaultSerializer() { if (defaultJsonSerializer == null) { synchronized (LOCK) { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } } return defaultJsonSerializer; } }
In the case of a null object do we want to throw or return an empty `BinaryData`? Do we want to force the caller to handle null checking or return them an object which represents no data.
public static BinaryData fromObject(Object data) { Objects.requireNonNull(data, "'data' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonSerializerProviders.createInstance().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
Objects.requireNonNull(data, "'data' cannot be null.");
public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private final byte[] data; /** * Create instance of {@link BinaryData} given the data. * @param data to represent as bytes. * @throws NullPointerException If {@code data} is null. */ BinaryData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = Arrays.copyOf(data, data.length); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /** * Provides {@link Mono} of {@link InputStream} for the data represented by this {@link BinaryData} object. * * @return {@link InputStream} representation of the {@link BinaryData}. */ public Mono<InputStream> toStreamAsync() { return Mono.fromCallable(() -> toStream()); } /** * Create {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} is * not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return fromBytes(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously create {@link BinaryData} instance with given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. * * @param inputStream to read bytes from. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Create {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return monoError(LOGGER, new NullPointerException("'data' cannot be null.")); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(fromBytes(bytes))); } /** * Create {@link BinaryData} instance with given data and character set. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @param charSet to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromString(String data, Charset charSet) { Objects.requireNonNull(data, "'data' cannot be null."); return new BinaryData(data.getBytes(charSet)); } /** * Create {@link BinaryData} instance with given data. The {@link String} is converted into bytes using * {@link StandardCharsets * * @param data to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { Objects.requireNonNull(data, "'data' cannot be null."); return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Create {@link BinaryData} instance with given byte array data. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(data); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link JsonSerializer}. This will * require the client to configure Json serializer in classpath. * * @param data The {@link Object} which needs to be serialized into bytes. * @throws NullPointerException if {@code data} is null. * @throws IllegalStateException If cannot find any JSON serializer provider on the classpath. * @return {@link BinaryData} representing binary data. Or {@code null} if it fails to serialize the data. * * @see JsonSerializer */ /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code inputStream} or {@code serializer} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { Objects.requireNonNull(data, "'data' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code inputStream} or {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { Objects.requireNonNull(data, "'data' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using {@link StandardCharsets * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Provides {@link String} representation of this {@link BinaryData} object given a character set. * * @param charSet to use to convert bytes into {@link String}. * @return {@link String} representation of the the binary data. */ public String toString(Charset charSet) { return new String(this.data, charSet); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the provided * {@link ObjectSerializer} on the {@link BinaryData}. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException if {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { return Mono.fromCallable(() -> toObject(clazz, serializer)); } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]); private static final Object LOCK = new Object(); private final byte[] data; private static volatile JsonSerializer defaultJsonSerializer; /** * Create an instance of {@link BinaryData} from the given data. * * @param data to represent as bytes. */ BinaryData(byte[] data) { this.data = data; } /** * Creates a {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} * is not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { if (Objects.isNull(inputStream)) { return EMPTY_DATA; } final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } dataOutputBuffer.flush(); return new BinaryData(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously creates a {@link BinaryData} instance with the given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. If the {@link InputStream} is {@code null}, an empty * {@link BinaryData} will be returned. * * @param inputStream to read bytes from. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates a {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. If the {@link Flux} is {@code null}, an * empty {@link BinaryData} will be returned. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return Mono.just(EMPTY_DATA); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(new BinaryData(bytes))); } /** * Creates a {@link BinaryData} instance with given data. The {@link String} is converted into bytes using UTF_8 * character set. If the String is {@code null}, an empty {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { if (Objects.isNull(data) || data.length() == 0) { return EMPTY_DATA; } return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Creates a {@link BinaryData} instance with given byte array data. If the byte array is {@code null}, an empty * {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { if (Objects.isNull(data) || data.length == 0) { return EMPTY_DATA; } return new BinaryData(Arrays.copyOf(data, data.length)); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available on classpath. * The serializer on classpath must implement {@link JsonSerializer} interface. If the given Object is {@code null}, * an empty {@link BinaryData} will be returned. * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from.default.serializer * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing the JSON serialized object. * * @see JsonSerializer * @see <a href="ObjectSerializer" target="_blank">More about serialization</a> */ /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If the Object is {@code null}, an empty {@link BinaryData} will be returned. * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Create an instance from Object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link BinaryData} representing binary data. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return EMPTY_DATA; } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. * @see ObjectSerializer * @see <a href="https: */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using the UTF-8 character set. * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code serializer} or {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the * provided {@link ObjectSerializer} on the {@link BinaryData}. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by using json serializer which is available in * classpath. The serializer must implement {@link JsonSerializer} interface. A singleton instance of * {@link JsonSerializer} is kept for this class to use. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return getDefaultSerializer().deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz)); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */ private static JsonSerializer getDefaultSerializer() { if (defaultJsonSerializer == null) { synchronized (LOCK) { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } } return defaultJsonSerializer; } }
Set up a meeting for next week and we can discuss this and work on some guidelines text.
public static BinaryData fromObject(Object data) { Objects.requireNonNull(data, "'data' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonSerializerProviders.createInstance().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
JsonSerializerProviders.createInstance().serialize(outputStream, data);
public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private final byte[] data; /** * Create instance of {@link BinaryData} given the data. * @param data to represent as bytes. * @throws NullPointerException If {@code data} is null. */ BinaryData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = Arrays.copyOf(data, data.length); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /** * Provides {@link Mono} of {@link InputStream} for the data represented by this {@link BinaryData} object. * * @return {@link InputStream} representation of the {@link BinaryData}. */ public Mono<InputStream> toStreamAsync() { return Mono.fromCallable(() -> toStream()); } /** * Create {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} is * not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return fromBytes(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously create {@link BinaryData} instance with given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. * * @param inputStream to read bytes from. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Create {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return monoError(LOGGER, new NullPointerException("'data' cannot be null.")); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(fromBytes(bytes))); } /** * Create {@link BinaryData} instance with given data and character set. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @param charSet to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromString(String data, Charset charSet) { Objects.requireNonNull(data, "'data' cannot be null."); return new BinaryData(data.getBytes(charSet)); } /** * Create {@link BinaryData} instance with given data. The {@link String} is converted into bytes using * {@link StandardCharsets * * @param data to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { Objects.requireNonNull(data, "'data' cannot be null."); return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Create {@link BinaryData} instance with given byte array data. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(data); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link JsonSerializer}. This will * require the client to configure Json serializer in classpath. * * @param data The {@link Object} which needs to be serialized into bytes. * @throws NullPointerException if {@code data} is null. * @throws IllegalStateException If cannot find any JSON serializer provider on the classpath. * @return {@link BinaryData} representing binary data. Or {@code null} if it fails to serialize the data. * * @see JsonSerializer */ /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code inputStream} or {@code serializer} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { Objects.requireNonNull(data, "'data' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code inputStream} or {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { Objects.requireNonNull(data, "'data' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using {@link StandardCharsets * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Provides {@link String} representation of this {@link BinaryData} object given a character set. * * @param charSet to use to convert bytes into {@link String}. * @return {@link String} representation of the the binary data. */ public String toString(Charset charSet) { return new String(this.data, charSet); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the provided * {@link ObjectSerializer} on the {@link BinaryData}. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException if {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { return Mono.fromCallable(() -> toObject(clazz, serializer)); } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]); private static final Object LOCK = new Object(); private final byte[] data; private static volatile JsonSerializer defaultJsonSerializer; /** * Create an instance of {@link BinaryData} from the given data. * * @param data to represent as bytes. */ BinaryData(byte[] data) { this.data = data; } /** * Creates a {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} * is not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { if (Objects.isNull(inputStream)) { return EMPTY_DATA; } final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } dataOutputBuffer.flush(); return new BinaryData(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously creates a {@link BinaryData} instance with the given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. If the {@link InputStream} is {@code null}, an empty * {@link BinaryData} will be returned. * * @param inputStream to read bytes from. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates a {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. If the {@link Flux} is {@code null}, an * empty {@link BinaryData} will be returned. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return Mono.just(EMPTY_DATA); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(new BinaryData(bytes))); } /** * Creates a {@link BinaryData} instance with given data. The {@link String} is converted into bytes using UTF_8 * character set. If the String is {@code null}, an empty {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { if (Objects.isNull(data) || data.length() == 0) { return EMPTY_DATA; } return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Creates a {@link BinaryData} instance with given byte array data. If the byte array is {@code null}, an empty * {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { if (Objects.isNull(data) || data.length == 0) { return EMPTY_DATA; } return new BinaryData(Arrays.copyOf(data, data.length)); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available on classpath. * The serializer on classpath must implement {@link JsonSerializer} interface. If the given Object is {@code null}, * an empty {@link BinaryData} will be returned. * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from.default.serializer * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing the JSON serialized object. * * @see JsonSerializer * @see <a href="ObjectSerializer" target="_blank">More about serialization</a> */ /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If the Object is {@code null}, an empty {@link BinaryData} will be returned. * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Create an instance from Object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link BinaryData} representing binary data. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return EMPTY_DATA; } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. * @see ObjectSerializer * @see <a href="https: */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using the UTF-8 character set. * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code serializer} or {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the * provided {@link ObjectSerializer} on the {@link BinaryData}. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by using json serializer which is available in * classpath. The serializer must implement {@link JsonSerializer} interface. A singleton instance of * {@link JsonSerializer} is kept for this class to use. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return getDefaultSerializer().deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz)); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */ private static JsonSerializer getDefaultSerializer() { if (defaultJsonSerializer == null) { synchronized (LOCK) { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } } return defaultJsonSerializer; } }
What does `getBytes` return for a zero length string?
public static BinaryData fromString(String data) { if (Objects.isNull(data)) { return new BinaryData(EMPTY_DATA); } else { return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } }
return new BinaryData(data.getBytes(StandardCharsets.UTF_8));
public static BinaryData fromString(String data) { if (Objects.isNull(data) || data.length() == 0) { return EMPTY_DATA; } return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static JsonSerializer defaultJsonSerializer; private static byte[] EMPTY_DATA = new byte[0]; private final byte[] data; /** * Create instance of {@link BinaryData} given the data. If {@code null} value is provided , it will be converted * into empty byte array. * @param data to represent as bytes. */ BinaryData(byte[] data) { if (Objects.isNull(data)) { data = EMPTY_DATA; } this.data = Arrays.copyOf(data, data.length); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /** * Create {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} is * not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException if {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return fromBytes(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously create {@link BinaryData} instance with given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. * * @param inputStream to read bytes from. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Create {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @throws NullPointerException if {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return monoError(LOGGER, new NullPointerException("'data' cannot be null.")); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(fromBytes(bytes))); } /** * Create {@link BinaryData} instance with given data. The {@link String} is converted into bytes using * {@link StandardCharsets * empty byte array. * * @param data to use. * @return {@link BinaryData} representing binary data. */ /** * Create {@link BinaryData} instance with given byte array data. If {@code null} value is provided , it will be * converted into empty byte array. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(data); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available in classpath. * The serializer must implement {@link JsonSerializer} interface. A singleton instance of {@link JsonSerializer} * is kept for this class to use. If {@code null} data is provided , it will be converted into empty byte array. * * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing binary data. * * @see JsonSerializer */ public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return new BinaryData(EMPTY_DATA); } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); loadDefaultSerializer(); defaultJsonSerializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If {@code null} data is provided , it will be converted into empty byte array. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code serializer} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return new BinaryData(EMPTY_DATA); } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If {@code null} data is provided , it will be converted into empty byte array. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException if {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using {@link StandardCharsets * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the provided * {@link ObjectSerializer} on the {@link BinaryData}. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException if {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. The serializer must implement {@link JsonSerializer} interface. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); loadDefaultSerializer(); return defaultJsonSerializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException if {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { return Mono.fromCallable(() -> toObject(clazz)); } private static void loadDefaultSerializer() { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]); private static final Object LOCK = new Object(); private final byte[] data; private static volatile JsonSerializer defaultJsonSerializer; /** * Create an instance of {@link BinaryData} from the given data. * * @param data to represent as bytes. */ BinaryData(byte[] data) { this.data = data; } /** * Creates a {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} * is not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromStream(InputStream inputStream) { if (Objects.isNull(inputStream)) { return EMPTY_DATA; } final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } dataOutputBuffer.flush(); return new BinaryData(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } /** * Asynchronously creates a {@link BinaryData} instance with the given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. If the {@link InputStream} is {@code null}, an empty * {@link BinaryData} will be returned. * * @param inputStream to read bytes from. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates a {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. If the {@link Flux} is {@code null}, an * empty {@link BinaryData} will be returned. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return Mono.just(EMPTY_DATA); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(new BinaryData(bytes))); } /** * Creates a {@link BinaryData} instance with given data. The {@link String} is converted into bytes using UTF_8 * character set. If the String is {@code null}, an empty {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing binary data. */ /** * Creates a {@link BinaryData} instance with given byte array data. If the byte array is {@code null}, an empty * {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { if (Objects.isNull(data) || data.length == 0) { return EMPTY_DATA; } return new BinaryData(Arrays.copyOf(data, data.length)); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available on classpath. * The serializer on classpath must implement {@link JsonSerializer} interface. If the given Object is {@code null}, * an empty {@link BinaryData} will be returned. * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from.default.serializer * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing the JSON serialized object. * * @see JsonSerializer * @see <a href="ObjectSerializer" target="_blank">More about serialization</a> */ public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If the Object is {@code null}, an empty {@link BinaryData} will be returned. * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Create an instance from Object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link BinaryData} representing binary data. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return EMPTY_DATA; } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. * @see ObjectSerializer * @see <a href="https: */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using the UTF-8 character set. * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code serializer} or {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the * provided {@link ObjectSerializer} on the {@link BinaryData}. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by using json serializer which is available in * classpath. The serializer must implement {@link JsonSerializer} interface. A singleton instance of * {@link JsonSerializer} is kept for this class to use. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return getDefaultSerializer().deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz)); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */ private static JsonSerializer getDefaultSerializer() { if (defaultJsonSerializer == null) { synchronized (LOCK) { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } } return defaultJsonSerializer; } }
Are we not able to handle this in a more efficient manner? As it stands this means that the entire input stream is read into a buffer, converted into a byte array, and then copied into a new byte array? At the very least you can avoid the byte array copy.
public static BinaryData fromStream(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return fromBytes(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }
}
public static BinaryData fromStream(InputStream inputStream) { if (Objects.isNull(inputStream)) { return EMPTY_DATA; } final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } dataOutputBuffer.flush(); return new BinaryData(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static final byte[] EMPTY_BYTES = new byte[0]; private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]); private static final Object LOCK = new Object(); private final byte[] data; private static volatile JsonSerializer defaultJsonSerializer; /** * Create an instance of {@link BinaryData} from the given data. If {@code null} value is provided , it will be * converted into empty byte array. * * @param data to represent as bytes. */ BinaryData(byte[] data) { if (Objects.isNull(data) || data.length == 0) { data = EMPTY_BYTES; } this.data = Arrays.copyOf(data, data.length); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /** * Creates a {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} * is not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ /** * Asynchronously create a {@link BinaryData} instance with given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. * * @param inputStream to read bytes from. * @throws NullPointerException If {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates a {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @throws NullPointerException If {@code data} is null. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return monoError(LOGGER, new NullPointerException("'data' cannot be null.")); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(fromBytes(bytes))); } /** * Creates a {@link BinaryData} instance with given data. The {@link String} is converted into bytes using UTF_8 * character set. If the String is {@code null}, an empty {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { if (Objects.isNull(data) || data.length() == 0) { return EMPTY_DATA; } else { return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } } /** * Creates a {@link BinaryData} instance with given byte array data. If the byte array is {@code null}, an empty * {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(data); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available on classpath. * The serializer on classpath must implement {@link JsonSerializer} interface. If the given Object is {@code null}, * an empty {@link BinaryData} will be returned. * * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing the JSON serialized object. * * @see JsonSerializer */ public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * <p><strong>Create an instance from Object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return EMPTY_DATA; } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using the UTF-8 character set. * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code serializer} or {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the provided * {@link ObjectSerializer} on the {@link BinaryData}. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by using json serializer which is available in * classpath. The serializer must implement {@link JsonSerializer} interface. A singleton instance of * {@link JsonSerializer} is kept for this class to use. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return getDefaultSerializer().deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz)); } /* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */ private static JsonSerializer getDefaultSerializer() { if (defaultJsonSerializer == null) { synchronized (LOCK) { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } } return defaultJsonSerializer; } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]); private static final Object LOCK = new Object(); private final byte[] data; private static volatile JsonSerializer defaultJsonSerializer; /** * Create an instance of {@link BinaryData} from the given data. * * @param data to represent as bytes. */ BinaryData(byte[] data) { this.data = data; } /** * Creates a {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} * is not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ /** * Asynchronously creates a {@link BinaryData} instance with the given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. If the {@link InputStream} is {@code null}, an empty * {@link BinaryData} will be returned. * * @param inputStream to read bytes from. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates a {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. If the {@link Flux} is {@code null}, an * empty {@link BinaryData} will be returned. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return Mono.just(EMPTY_DATA); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(new BinaryData(bytes))); } /** * Creates a {@link BinaryData} instance with given data. The {@link String} is converted into bytes using UTF_8 * character set. If the String is {@code null}, an empty {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { if (Objects.isNull(data) || data.length() == 0) { return EMPTY_DATA; } return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Creates a {@link BinaryData} instance with given byte array data. If the byte array is {@code null}, an empty * {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { if (Objects.isNull(data) || data.length == 0) { return EMPTY_DATA; } return new BinaryData(Arrays.copyOf(data, data.length)); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available on classpath. * The serializer on classpath must implement {@link JsonSerializer} interface. If the given Object is {@code null}, * an empty {@link BinaryData} will be returned. * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from.default.serializer * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing the JSON serialized object. * * @see JsonSerializer * @see <a href="ObjectSerializer" target="_blank">More about serialization</a> */ public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If the Object is {@code null}, an empty {@link BinaryData} will be returned. * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Create an instance from Object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link BinaryData} representing binary data. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return EMPTY_DATA; } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. * @see ObjectSerializer * @see <a href="https: */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using the UTF-8 character set. * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code serializer} or {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the * provided {@link ObjectSerializer} on the {@link BinaryData}. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by using json serializer which is available in * classpath. The serializer must implement {@link JsonSerializer} interface. A singleton instance of * {@link JsonSerializer} is kept for this class to use. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return getDefaultSerializer().deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz)); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */ private static JsonSerializer getDefaultSerializer() { if (defaultJsonSerializer == null) { synchronized (LOCK) { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } } return defaultJsonSerializer; } }
Removed the last byte array and same optimization in other from..() API as well.
public static BinaryData fromStream(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } return fromBytes(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }
}
public static BinaryData fromStream(InputStream inputStream) { if (Objects.isNull(inputStream)) { return EMPTY_DATA; } final int bufferSize = 1024; try { ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[bufferSize]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { dataOutputBuffer.write(data, 0, nRead); } dataOutputBuffer.flush(); return new BinaryData(dataOutputBuffer.toByteArray()); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static final byte[] EMPTY_BYTES = new byte[0]; private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]); private static final Object LOCK = new Object(); private final byte[] data; private static volatile JsonSerializer defaultJsonSerializer; /** * Create an instance of {@link BinaryData} from the given data. If {@code null} value is provided , it will be * converted into empty byte array. * * @param data to represent as bytes. */ BinaryData(byte[] data) { if (Objects.isNull(data) || data.length == 0) { data = EMPTY_BYTES; } this.data = Arrays.copyOf(data, data.length); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /** * Creates a {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} * is not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ /** * Asynchronously create a {@link BinaryData} instance with given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. * * @param inputStream to read bytes from. * @throws NullPointerException If {@code inputStream} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { Objects.requireNonNull(inputStream, "'inputStream' cannot be null."); return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates a {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @throws NullPointerException If {@code data} is null. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return monoError(LOGGER, new NullPointerException("'data' cannot be null.")); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(fromBytes(bytes))); } /** * Creates a {@link BinaryData} instance with given data. The {@link String} is converted into bytes using UTF_8 * character set. If the String is {@code null}, an empty {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { if (Objects.isNull(data) || data.length() == 0) { return EMPTY_DATA; } else { return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } } /** * Creates a {@link BinaryData} instance with given byte array data. If the byte array is {@code null}, an empty * {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(data); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available on classpath. * The serializer on classpath must implement {@link JsonSerializer} interface. If the given Object is {@code null}, * an empty {@link BinaryData} will be returned. * * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing the JSON serialized object. * * @see JsonSerializer */ public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * <p><strong>Create an instance from Object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return EMPTY_DATA; } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using the UTF-8 character set. * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code serializer} or {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the provided * {@link ObjectSerializer} on the {@link BinaryData}. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by using json serializer which is available in * classpath. The serializer must implement {@link JsonSerializer} interface. A singleton instance of * {@link JsonSerializer} is kept for this class to use. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return getDefaultSerializer().deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserialize the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz)); } /* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */ private static JsonSerializer getDefaultSerializer() { if (defaultJsonSerializer == null) { synchronized (LOCK) { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } } return defaultJsonSerializer; } }
class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]); private static final Object LOCK = new Object(); private final byte[] data; private static volatile JsonSerializer defaultJsonSerializer; /** * Create an instance of {@link BinaryData} from the given data. * * @param data to represent as bytes. */ BinaryData(byte[] data) { this.data = data; } /** * Creates a {@link BinaryData} instance with given {@link InputStream} as source of data. The {@link InputStream} * is not closed by this function. * * <p><strong>Create an instance from InputStream</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param inputStream to read bytes from. * @throws UncheckedIOException If any error in reading from {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. * @return {@link BinaryData} representing the binary data. */ /** * Asynchronously creates a {@link BinaryData} instance with the given {@link InputStream} as source of data. The * {@link InputStream} is not closed by this function. If the {@link InputStream} is {@code null}, an empty * {@link BinaryData} will be returned. * * @param inputStream to read bytes from. * @return {@link Mono} of {@link BinaryData} representing the binary data. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates a {@link BinaryData} instance with given {@link Flux} of {@link ByteBuffer} as source of data. It will * collect all the bytes from {@link ByteBuffer} into {@link BinaryData}. If the {@link Flux} is {@code null}, an * empty {@link BinaryData} will be returned. * * <p><strong>Create an instance from String</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data to use. * @return {@link Mono} of {@link BinaryData} representing binary data. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (Objects.isNull(data)) { return Mono.just(EMPTY_DATA); } return FluxUtil.collectBytesInByteBufferStream(data) .flatMap(bytes -> Mono.just(new BinaryData(bytes))); } /** * Creates a {@link BinaryData} instance with given data. The {@link String} is converted into bytes using UTF_8 * character set. If the String is {@code null}, an empty {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing binary data. */ public static BinaryData fromString(String data) { if (Objects.isNull(data) || data.length() == 0) { return EMPTY_DATA; } return new BinaryData(data.getBytes(StandardCharsets.UTF_8)); } /** * Creates a {@link BinaryData} instance with given byte array data. If the byte array is {@code null}, an empty * {@link BinaryData} will be returned. * * @param data to use. * @return {@link BinaryData} representing the binary data. */ public static BinaryData fromBytes(byte[] data) { if (Objects.isNull(data) || data.length == 0) { return EMPTY_DATA; } return new BinaryData(Arrays.copyOf(data, data.length)); } /** * Serialize the given {@link Object} into {@link BinaryData} using json serializer which is available on classpath. * The serializer on classpath must implement {@link JsonSerializer} interface. If the given Object is {@code null}, * an empty {@link BinaryData} will be returned. * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from.default.serializer * @param data The {@link Object} which needs to be serialized into bytes. * @throws IllegalStateException If a {@link JsonSerializer} cannot be found on the classpath. * @return {@link BinaryData} representing the JSON serialized object. * * @see JsonSerializer * @see <a href="ObjectSerializer" target="_blank">More about serialization</a> */ public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link BinaryData} using the provided {@link ObjectSerializer}. * If the Object is {@code null}, an empty {@link BinaryData} will be returned. * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Create an instance from Object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.from * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link BinaryData} representing binary data. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https: */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { if (Objects.isNull(data)) { return EMPTY_DATA; } Objects.requireNonNull(serializer, "'serializer' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); } /** * Serialize the given {@link Object} into {@link Mono} {@link BinaryData} using the provided * {@link ObjectSerializer}. If the Object is {@code null}, an empty {@link BinaryData} will be returned. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * @param data The {@link Object} which needs to be serialized into bytes. * @param serializer to use for serializing the object. * @throws NullPointerException If {@code serializer} is null. * @return {@link Mono} of {@link BinaryData} representing the binary data. * @see ObjectSerializer * @see <a href="https: */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Provides byte array representation of this {@link BinaryData} object. * * @return byte array representation of the the data. */ public byte[] toBytes() { return Arrays.copyOf(this.data, this.data.length); } /** * Provides {@link String} representation of this {@link BinaryData} object. The bytes are converted into * {@link String} using the UTF-8 character set. * * @return {@link String} representation of the data. */ public String toString() { return new String(this.data, StandardCharsets.UTF_8); } /** * Deserialize the bytes into the {@link Object} of given type by applying the provided {@link ObjectSerializer} on * the data. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code serializer} or {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return serializer.deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the * provided {@link ObjectSerializer} on the {@link BinaryData}. * * <p>You can provide your custom implementation of {@link ObjectSerializer} interface or use one provided in azure * sdk by adding them as dependency. These implementations could be found at * <a href="https: * and <a href="https: * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param serializer to use deserialize data into type. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); } /** * Deserialize the bytes into the {@link Object} of given type by using json serializer which is available in * classpath. The serializer must implement {@link JsonSerializer} interface. A singleton instance of * {@link JsonSerializer} is kept for this class to use. * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> T toObject(Class<T> clazz) { Objects.requireNonNull(clazz, "'clazz' cannot be null."); TypeReference<T> ref = TypeReference.createInstance(clazz); InputStream jsonStream = new ByteArrayInputStream(this.data); return getDefaultSerializer().deserialize(jsonStream, ref); } /** * Return a {@link Mono} by deserializing the bytes into the {@link Object} of given type after applying the Json * serializer found on classpath. * * <p><strong>Gets the specified object</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @param clazz representing the type of the Object. * @param <T> Generic type that the data is deserialized into. * @throws NullPointerException If {@code clazz} is null. * @return The {@link Object} of given type after deserializing the bytes. */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz)); } /** * Provides {@link InputStream} for the data represented by this {@link BinaryData} object. * * <p><strong>Get InputStream from BinaryData</strong></p> * {@codesnippet com.azure.core.experimental.util.BinaryDocument.to * * @return {@link InputStream} representing the binary data. */ public InputStream toStream() { return new ByteArrayInputStream(this.data); } /* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */ private static JsonSerializer getDefaultSerializer() { if (defaultJsonSerializer == null) { synchronized (LOCK) { if (defaultJsonSerializer == null) { defaultJsonSerializer = JsonSerializerProviders.createInstance(); } } } return defaultJsonSerializer; } }
The problem with removing this line is that if someone does: ```java var client = new ServiceBusClientBuilder().configuration(null) .buildClient(); ``` It won't use the default credential because you only assign it on object creation.
private ConnectionOptions getConnectionOptions() { if (credentials == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "or credentials(String, String, TokenCredential)" )); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP.")); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler, options, SslDomain.VerifyMode.VERIFY_PEER_NAME); }
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
private ConnectionOptions getConnectionOptions() { configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "or credentials(String, String, TokenCredential)" )); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP.")); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler, options, SslDomain.VerifyMode.VERIFY_PEER_NAME); }
class ServiceBusClientBuilder { private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT); private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties"; private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s"; private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue"; private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue"; private static final int DEFAULT_PREFETCH_COUNT = 1; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final Object connectionLock = new Object(); private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class); private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer(); private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); private ClientOptions clientOptions; private Configuration configuration = Configuration.getGlobalConfiguration().clone(); private ServiceBusConnectionProcessor sharedConnection; private String connectionStringEntityName; private TokenCredential credentials; private String fullyQualifiedNamespace; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport = AmqpTransportType.AMQP; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType */ public ServiceBusClientBuilder() { } /** * Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of * certain properties, as well as support the addition of custom header information. Refer to the * {@link ClientOptions} documentation for more information. * * @param clientOptions to be set on the client. * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the connection string for a Service Bus namespace or a specific Service Bus resource. * * @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential; try { tokenCredential = getTokenCredential(properties); } catch (Exception e) { throw logger.logExceptionAsError( new AzureException("Could not create the ServiceBusSharedKeyCredential.", e)); } this.fullyQualifiedNamespace = properties.getEndpoint().getHost(); if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) { logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath()); this.connectionStringEntityName = properties.getEntityPath(); } return credential(properties.getEndpoint().getHost(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY); } else { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure Service Bus clients. Use * {@link Configuration * * @param configuration The configuration store used to configure Service Bus clients. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the credential for the Service Bus resource. * * @param fullyQualifiedNamespace for the Service Bus. * @param credential {@link TokenCredential} to be used for authentication. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the retry options for Service Bus clients. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the scheduler to use. * * @param scheduler Scheduler to be used. * * @return The updated {@link ServiceBusClientBuilder} object. */ ServiceBusClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link * AmqpTransportType * * @param transportType The transport type to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder transportType(AmqpTransportType transportType) { this.transport = transportType; return this; } /** * A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders. * * @return A new instance of {@link ServiceBusSenderClientBuilder}. */ public ServiceBusSenderClientBuilder sender() { return new ServiceBusSenderClientBuilder(); } /** * A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message consumers. * * @return A new instance of {@link ServiceBusReceiverClientBuilder}. */ public ServiceBusReceiverClientBuilder receiver() { return new ServiceBusReceiverClientBuilder(); } /** * A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service * Bus message consumers. * * @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}. */ public ServiceBusSessionReceiverClientBuilder sessionReceiver() { return new ServiceBusSessionReceiverClientBuilder(); } /** * Called when a child client is closed. Disposes of the shared connection if there are no more clients. */ void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection [{}].", sharedConnection); if (sharedConnection != null) { sharedConnection.dispose(); sharedConnection = null; } else { logger.warning("Shared ServiceBusConnectionProcessor was already disposed."); } } } private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } synchronized (connectionLock) { if (sharedConnection == null) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> { final String connectionId = StringUtil.getRandomString("MF"); return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId, connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer, product, clientVersion); }).repeat(); sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry())); } } final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" return sharedConnection; } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } } private static boolean isNullOrEmpty(String item) { return item == null || item.isEmpty(); } private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName, String topicName, String queueName) { final boolean hasTopicName = !isNullOrEmpty(topicName); final boolean hasQueueName = !isNullOrEmpty(queueName); final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName); final MessagingEntityType entityType; if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) { throw logger.logExceptionAsError(new IllegalStateException( "Cannot build client without setting either a queueName or topicName.")); } else if (hasQueueName && hasTopicName) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName))); } else if (hasQueueName) { if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "queueName (%s) is different than the connectionString's EntityPath (%s).", queueName, connectionStringEntityName))); } entityType = MessagingEntityType.QUEUE; } else if (hasTopicName) { if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) is different than the connectionString's EntityPath (%s).", topicName, connectionStringEntityName))); } entityType = MessagingEntityType.SUBSCRIPTION; } else { entityType = MessagingEntityType.UNKNOWN; } return entityType; } private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName, String topicName, String subscriptionName, SubQueue subQueue) { String entityPath; switch (entityType) { case QUEUE: entityPath = queueName; break; case SUBSCRIPTION: if (isNullOrEmpty(subscriptionName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) must have a subscriptionName associated with it.", topicName))); } entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName, subscriptionName); break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } if (subQueue == null) { return entityPath; } switch (subQueue) { case NONE: break; case TRANSFER_DEAD_LETTER_QUEUE: entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX; break; case DEAD_LETTER_QUEUE: entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX; break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: " + subQueue)); } return entityPath; } /** * Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages * to Service Bus. * * @see ServiceBusSenderAsyncClient * @see ServiceBusSenderClient */ @ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class}) public final class ServiceBusSenderClientBuilder { private String queueName; private String topicName; private String viaQueueName; private String viaTopicName; private ServiceBusSenderClientBuilder() { } /** * Sets the name of the Service Bus queue to publish messages to. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSenderClientBuilder} object. */ public ServiceBusSenderClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the name of the initial destination Service Bus queue to publish messages to. * * @param viaQueueName The initial destination of the message. * * @return The modified {@link ServiceBusSenderClientBuilder} object. * * @see <a href="https: */ public ServiceBusSenderClientBuilder viaQueueName(String viaQueueName) { this.viaQueueName = viaQueueName; return this; } /** * Sets the name of the initial destination Service Bus topic to publish messages to. * * @param viaTopicName The initial destination of the message. * * @return The modified {@link ServiceBusSenderClientBuilder} object. * * @see <a href="https: */ public ServiceBusSenderClientBuilder viaTopicName(String viaTopicName) { this.viaTopicName = viaTopicName; return this; } /** * Sets the name of the Service Bus topic to publish messages to. * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSenderClientBuilder} object. */ public ServiceBusSenderClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link * ServiceBusMessage} to a Service Bus queue or topic. * * @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * {@link * @throws IllegalArgumentException if the entity type is not a queue or a topic. */ public ServiceBusSenderAsyncClient buildAsyncClient() { final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); if (!CoreUtils.isNullOrEmpty(viaQueueName) && entityType == MessagingEntityType.SUBSCRIPTION) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "(%s), Via queue feature work only with a queue.", viaQueueName))); } else if (!CoreUtils.isNullOrEmpty(viaTopicName) && entityType == MessagingEntityType.QUEUE) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "(%s), Via topic feature work only with a topic.", viaTopicName))); } final String entityName; final String viaEntityName = !CoreUtils.isNullOrEmpty(viaQueueName) ? viaQueueName : viaTopicName; switch (entityType) { case QUEUE: entityName = queueName; break; case SUBSCRIPTION: entityName = topicName; break; case UNKNOWN: entityName = connectionStringEntityName; break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, viaEntityName); } /** * Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage} * to a Service Bus queue or topic. * * @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * @throws IllegalArgumentException if the entity type is not a queue or a topic. */ public ServiceBusSenderClient buildClient() { return new ServiceBusSenderClient(buildAsyncClient(), retryOptions.getTryTimeout()); } } /** * Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume * messages from a <b>session aware</b> Service Bus entity. * * @see ServiceBusReceiverAsyncClient * @see ServiceBusReceiverClient */ @ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class}) public final class ServiceBusSessionReceiverClientBuilder { private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private ServiceBusSessionReceiverClientBuilder() { } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading * {@link ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); validateAndThrow(prefetchCount); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); if (CoreUtils.isNullOrEmpty(sessionId)) { final UnnamedSessionManager sessionManager = new UnnamedSessionManager(entityPath, entityType, connectionProcessor, connectionProcessor.getRetryOptions().getTryTimeout(), tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); } else { return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading * {@link ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(), retryOptions.getTryTimeout()); } /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } } /** * Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume * messages from Service Bus. * * @see ServiceBusReceiverAsyncClient * @see ServiceBusReceiverClient */ @ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class}) public final class ServiceBusReceiverClientBuilder { private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private SubQueue subQueue; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String subscriptionName; private String topicName; private ServiceBusReceiverClientBuilder() { } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the type of the {@link SubQueue} to connect to. * * @param subQueue The type of the sub queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) { this.subQueue = subQueue; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage * messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, subQueue); validateAndThrow(prefetchCount); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } /** * Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages} * from a specific queue or topic. * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(), retryOptions.getTryTimeout()); } } private void validateAndThrow(int prefetchCount) { if (prefetchCount < 1) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "prefetchCount (%s) cannot be less than 1.", prefetchCount))); } } }
class ServiceBusClientBuilder { private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT); private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties"; private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s"; private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue"; private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue"; private static final int DEFAULT_PREFETCH_COUNT = 1; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final Object connectionLock = new Object(); private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class); private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer(); private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); private ClientOptions clientOptions; private Configuration configuration; private ServiceBusConnectionProcessor sharedConnection; private String connectionStringEntityName; private TokenCredential credentials; private String fullyQualifiedNamespace; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport = AmqpTransportType.AMQP; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType */ public ServiceBusClientBuilder() { } /** * Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of * certain properties, as well as support the addition of custom header information. Refer to the * {@link ClientOptions} documentation for more information. * * @param clientOptions to be set on the client. * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the connection string for a Service Bus namespace or a specific Service Bus resource. * * @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential; try { tokenCredential = getTokenCredential(properties); } catch (Exception e) { throw logger.logExceptionAsError( new AzureException("Could not create the ServiceBusSharedKeyCredential.", e)); } this.fullyQualifiedNamespace = properties.getEndpoint().getHost(); if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) { logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath()); this.connectionStringEntityName = properties.getEntityPath(); } return credential(properties.getEndpoint().getHost(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY); } else { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure Service Bus clients. Use * {@link Configuration * * @param configuration The configuration store used to configure Service Bus clients. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the credential for the Service Bus resource. * * @param fullyQualifiedNamespace for the Service Bus. * @param credential {@link TokenCredential} to be used for authentication. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the retry options for Service Bus clients. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the scheduler to use. * * @param scheduler Scheduler to be used. * * @return The updated {@link ServiceBusClientBuilder} object. */ ServiceBusClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link * AmqpTransportType * * @param transportType The transport type to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder transportType(AmqpTransportType transportType) { this.transport = transportType; return this; } /** * A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders. * * @return A new instance of {@link ServiceBusSenderClientBuilder}. */ public ServiceBusSenderClientBuilder sender() { return new ServiceBusSenderClientBuilder(); } /** * A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message consumers. * * @return A new instance of {@link ServiceBusReceiverClientBuilder}. */ public ServiceBusReceiverClientBuilder receiver() { return new ServiceBusReceiverClientBuilder(); } /** * A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service * Bus message consumers. * * @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}. */ public ServiceBusSessionReceiverClientBuilder sessionReceiver() { return new ServiceBusSessionReceiverClientBuilder(); } /** * Called when a child client is closed. Disposes of the shared connection if there are no more clients. */ void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection [{}].", sharedConnection); if (sharedConnection != null) { sharedConnection.dispose(); sharedConnection = null; } else { logger.warning("Shared ServiceBusConnectionProcessor was already disposed."); } } } private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } synchronized (connectionLock) { if (sharedConnection == null) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> { final String connectionId = StringUtil.getRandomString("MF"); return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId, connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer, product, clientVersion); }).repeat(); sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry())); } } final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" return sharedConnection; } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } } private static boolean isNullOrEmpty(String item) { return item == null || item.isEmpty(); } private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName, String topicName, String queueName) { final boolean hasTopicName = !isNullOrEmpty(topicName); final boolean hasQueueName = !isNullOrEmpty(queueName); final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName); final MessagingEntityType entityType; if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) { throw logger.logExceptionAsError(new IllegalStateException( "Cannot build client without setting either a queueName or topicName.")); } else if (hasQueueName && hasTopicName) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName))); } else if (hasQueueName) { if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "queueName (%s) is different than the connectionString's EntityPath (%s).", queueName, connectionStringEntityName))); } entityType = MessagingEntityType.QUEUE; } else if (hasTopicName) { if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) is different than the connectionString's EntityPath (%s).", topicName, connectionStringEntityName))); } entityType = MessagingEntityType.SUBSCRIPTION; } else { entityType = MessagingEntityType.UNKNOWN; } return entityType; } private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName, String topicName, String subscriptionName, SubQueue subQueue) { String entityPath; switch (entityType) { case QUEUE: entityPath = queueName; break; case SUBSCRIPTION: if (isNullOrEmpty(subscriptionName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) must have a subscriptionName associated with it.", topicName))); } entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName, subscriptionName); break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } if (subQueue == null) { return entityPath; } switch (subQueue) { case NONE: break; case TRANSFER_DEAD_LETTER_QUEUE: entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX; break; case DEAD_LETTER_QUEUE: entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX; break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: " + subQueue)); } return entityPath; } /** * Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages * to Service Bus. * * @see ServiceBusSenderAsyncClient * @see ServiceBusSenderClient */ @ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class}) public final class ServiceBusSenderClientBuilder { private String queueName; private String topicName; private String viaQueueName; private String viaTopicName; private ServiceBusSenderClientBuilder() { } /** * Sets the name of the Service Bus queue to publish messages to. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSenderClientBuilder} object. */ public ServiceBusSenderClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the name of the initial destination Service Bus queue to publish messages to. * * @param viaQueueName The initial destination of the message. * * @return The modified {@link ServiceBusSenderClientBuilder} object. * * @see <a href="https: */ public ServiceBusSenderClientBuilder viaQueueName(String viaQueueName) { this.viaQueueName = viaQueueName; return this; } /** * Sets the name of the initial destination Service Bus topic to publish messages to. * * @param viaTopicName The initial destination of the message. * * @return The modified {@link ServiceBusSenderClientBuilder} object. * * @see <a href="https: */ public ServiceBusSenderClientBuilder viaTopicName(String viaTopicName) { this.viaTopicName = viaTopicName; return this; } /** * Sets the name of the Service Bus topic to publish messages to. * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSenderClientBuilder} object. */ public ServiceBusSenderClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link * ServiceBusMessage} to a Service Bus queue or topic. * * @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * {@link * @throws IllegalArgumentException if the entity type is not a queue or a topic. */ public ServiceBusSenderAsyncClient buildAsyncClient() { final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); if (!CoreUtils.isNullOrEmpty(viaQueueName) && entityType == MessagingEntityType.SUBSCRIPTION) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "(%s), Via queue feature work only with a queue.", viaQueueName))); } else if (!CoreUtils.isNullOrEmpty(viaTopicName) && entityType == MessagingEntityType.QUEUE) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "(%s), Via topic feature work only with a topic.", viaTopicName))); } final String entityName; final String viaEntityName = !CoreUtils.isNullOrEmpty(viaQueueName) ? viaQueueName : viaTopicName; switch (entityType) { case QUEUE: entityName = queueName; break; case SUBSCRIPTION: entityName = topicName; break; case UNKNOWN: entityName = connectionStringEntityName; break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, viaEntityName); } /** * Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage} * to a Service Bus queue or topic. * * @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * @throws IllegalArgumentException if the entity type is not a queue or a topic. */ public ServiceBusSenderClient buildClient() { return new ServiceBusSenderClient(buildAsyncClient(), retryOptions.getTryTimeout()); } } /** * Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume * messages from a <b>session aware</b> Service Bus entity. * * @see ServiceBusReceiverAsyncClient * @see ServiceBusReceiverClient */ @ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class}) public final class ServiceBusSessionReceiverClientBuilder { private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private ServiceBusSessionReceiverClientBuilder() { } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading * {@link ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); validateAndThrow(prefetchCount); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); if (CoreUtils.isNullOrEmpty(sessionId)) { final UnnamedSessionManager sessionManager = new UnnamedSessionManager(entityPath, entityType, connectionProcessor, connectionProcessor.getRetryOptions().getTryTimeout(), tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); } else { return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading * {@link ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(), retryOptions.getTryTimeout()); } /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } } /** * Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume * messages from Service Bus. * * @see ServiceBusReceiverAsyncClient * @see ServiceBusReceiverClient */ @ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class}) public final class ServiceBusReceiverClientBuilder { private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private SubQueue subQueue; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String subscriptionName; private String topicName; private ServiceBusReceiverClientBuilder() { } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the type of the {@link SubQueue} to connect to. * * @param subQueue The type of the sub queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) { this.subQueue = subQueue; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage * messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, subQueue); validateAndThrow(prefetchCount); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } /** * Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages} * from a specific queue or topic. * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(), retryOptions.getTryTimeout()); } } private void validateAndThrow(int prefetchCount) { if (prefetchCount < 1) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "prefetchCount (%s) cannot be less than 1.", prefetchCount))); } } }
Added the line back
private ConnectionOptions getConnectionOptions() { if (credentials == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "or credentials(String, String, TokenCredential)" )); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP.")); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler, options, SslDomain.VerifyMode.VERIFY_PEER_NAME); }
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
private ConnectionOptions getConnectionOptions() { configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "or credentials(String, String, TokenCredential)" )); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP.")); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler, options, SslDomain.VerifyMode.VERIFY_PEER_NAME); }
class ServiceBusClientBuilder { private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT); private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties"; private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s"; private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue"; private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue"; private static final int DEFAULT_PREFETCH_COUNT = 1; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final Object connectionLock = new Object(); private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class); private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer(); private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); private ClientOptions clientOptions; private Configuration configuration = Configuration.getGlobalConfiguration().clone(); private ServiceBusConnectionProcessor sharedConnection; private String connectionStringEntityName; private TokenCredential credentials; private String fullyQualifiedNamespace; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport = AmqpTransportType.AMQP; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType */ public ServiceBusClientBuilder() { } /** * Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of * certain properties, as well as support the addition of custom header information. Refer to the * {@link ClientOptions} documentation for more information. * * @param clientOptions to be set on the client. * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the connection string for a Service Bus namespace or a specific Service Bus resource. * * @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential; try { tokenCredential = getTokenCredential(properties); } catch (Exception e) { throw logger.logExceptionAsError( new AzureException("Could not create the ServiceBusSharedKeyCredential.", e)); } this.fullyQualifiedNamespace = properties.getEndpoint().getHost(); if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) { logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath()); this.connectionStringEntityName = properties.getEntityPath(); } return credential(properties.getEndpoint().getHost(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY); } else { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure Service Bus clients. Use * {@link Configuration * * @param configuration The configuration store used to configure Service Bus clients. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the credential for the Service Bus resource. * * @param fullyQualifiedNamespace for the Service Bus. * @param credential {@link TokenCredential} to be used for authentication. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the retry options for Service Bus clients. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the scheduler to use. * * @param scheduler Scheduler to be used. * * @return The updated {@link ServiceBusClientBuilder} object. */ ServiceBusClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link * AmqpTransportType * * @param transportType The transport type to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder transportType(AmqpTransportType transportType) { this.transport = transportType; return this; } /** * A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders. * * @return A new instance of {@link ServiceBusSenderClientBuilder}. */ public ServiceBusSenderClientBuilder sender() { return new ServiceBusSenderClientBuilder(); } /** * A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message consumers. * * @return A new instance of {@link ServiceBusReceiverClientBuilder}. */ public ServiceBusReceiverClientBuilder receiver() { return new ServiceBusReceiverClientBuilder(); } /** * A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service * Bus message consumers. * * @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}. */ public ServiceBusSessionReceiverClientBuilder sessionReceiver() { return new ServiceBusSessionReceiverClientBuilder(); } /** * Called when a child client is closed. Disposes of the shared connection if there are no more clients. */ void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection [{}].", sharedConnection); if (sharedConnection != null) { sharedConnection.dispose(); sharedConnection = null; } else { logger.warning("Shared ServiceBusConnectionProcessor was already disposed."); } } } private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } synchronized (connectionLock) { if (sharedConnection == null) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> { final String connectionId = StringUtil.getRandomString("MF"); return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId, connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer, product, clientVersion); }).repeat(); sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry())); } } final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" return sharedConnection; } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } } private static boolean isNullOrEmpty(String item) { return item == null || item.isEmpty(); } private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName, String topicName, String queueName) { final boolean hasTopicName = !isNullOrEmpty(topicName); final boolean hasQueueName = !isNullOrEmpty(queueName); final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName); final MessagingEntityType entityType; if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) { throw logger.logExceptionAsError(new IllegalStateException( "Cannot build client without setting either a queueName or topicName.")); } else if (hasQueueName && hasTopicName) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName))); } else if (hasQueueName) { if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "queueName (%s) is different than the connectionString's EntityPath (%s).", queueName, connectionStringEntityName))); } entityType = MessagingEntityType.QUEUE; } else if (hasTopicName) { if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) is different than the connectionString's EntityPath (%s).", topicName, connectionStringEntityName))); } entityType = MessagingEntityType.SUBSCRIPTION; } else { entityType = MessagingEntityType.UNKNOWN; } return entityType; } private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName, String topicName, String subscriptionName, SubQueue subQueue) { String entityPath; switch (entityType) { case QUEUE: entityPath = queueName; break; case SUBSCRIPTION: if (isNullOrEmpty(subscriptionName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) must have a subscriptionName associated with it.", topicName))); } entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName, subscriptionName); break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } if (subQueue == null) { return entityPath; } switch (subQueue) { case NONE: break; case TRANSFER_DEAD_LETTER_QUEUE: entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX; break; case DEAD_LETTER_QUEUE: entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX; break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: " + subQueue)); } return entityPath; } /** * Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages * to Service Bus. * * @see ServiceBusSenderAsyncClient * @see ServiceBusSenderClient */ @ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class}) public final class ServiceBusSenderClientBuilder { private String queueName; private String topicName; private String viaQueueName; private String viaTopicName; private ServiceBusSenderClientBuilder() { } /** * Sets the name of the Service Bus queue to publish messages to. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSenderClientBuilder} object. */ public ServiceBusSenderClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the name of the initial destination Service Bus queue to publish messages to. * * @param viaQueueName The initial destination of the message. * * @return The modified {@link ServiceBusSenderClientBuilder} object. * * @see <a href="https: */ public ServiceBusSenderClientBuilder viaQueueName(String viaQueueName) { this.viaQueueName = viaQueueName; return this; } /** * Sets the name of the initial destination Service Bus topic to publish messages to. * * @param viaTopicName The initial destination of the message. * * @return The modified {@link ServiceBusSenderClientBuilder} object. * * @see <a href="https: */ public ServiceBusSenderClientBuilder viaTopicName(String viaTopicName) { this.viaTopicName = viaTopicName; return this; } /** * Sets the name of the Service Bus topic to publish messages to. * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSenderClientBuilder} object. */ public ServiceBusSenderClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link * ServiceBusMessage} to a Service Bus queue or topic. * * @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * {@link * @throws IllegalArgumentException if the entity type is not a queue or a topic. */ public ServiceBusSenderAsyncClient buildAsyncClient() { final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); if (!CoreUtils.isNullOrEmpty(viaQueueName) && entityType == MessagingEntityType.SUBSCRIPTION) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "(%s), Via queue feature work only with a queue.", viaQueueName))); } else if (!CoreUtils.isNullOrEmpty(viaTopicName) && entityType == MessagingEntityType.QUEUE) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "(%s), Via topic feature work only with a topic.", viaTopicName))); } final String entityName; final String viaEntityName = !CoreUtils.isNullOrEmpty(viaQueueName) ? viaQueueName : viaTopicName; switch (entityType) { case QUEUE: entityName = queueName; break; case SUBSCRIPTION: entityName = topicName; break; case UNKNOWN: entityName = connectionStringEntityName; break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, viaEntityName); } /** * Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage} * to a Service Bus queue or topic. * * @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * @throws IllegalArgumentException if the entity type is not a queue or a topic. */ public ServiceBusSenderClient buildClient() { return new ServiceBusSenderClient(buildAsyncClient(), retryOptions.getTryTimeout()); } } /** * Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume * messages from a <b>session aware</b> Service Bus entity. * * @see ServiceBusReceiverAsyncClient * @see ServiceBusReceiverClient */ @ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class}) public final class ServiceBusSessionReceiverClientBuilder { private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private ServiceBusSessionReceiverClientBuilder() { } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading * {@link ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); validateAndThrow(prefetchCount); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); if (CoreUtils.isNullOrEmpty(sessionId)) { final UnnamedSessionManager sessionManager = new UnnamedSessionManager(entityPath, entityType, connectionProcessor, connectionProcessor.getRetryOptions().getTryTimeout(), tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); } else { return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading * {@link ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(), retryOptions.getTryTimeout()); } /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } } /** * Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume * messages from Service Bus. * * @see ServiceBusReceiverAsyncClient * @see ServiceBusReceiverClient */ @ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class}) public final class ServiceBusReceiverClientBuilder { private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private SubQueue subQueue; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String subscriptionName; private String topicName; private ServiceBusReceiverClientBuilder() { } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the type of the {@link SubQueue} to connect to. * * @param subQueue The type of the sub queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) { this.subQueue = subQueue; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage * messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, subQueue); validateAndThrow(prefetchCount); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } /** * Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages} * from a specific queue or topic. * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(), retryOptions.getTryTimeout()); } } private void validateAndThrow(int prefetchCount) { if (prefetchCount < 1) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "prefetchCount (%s) cannot be less than 1.", prefetchCount))); } } }
class ServiceBusClientBuilder { private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT); private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties"; private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s"; private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue"; private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue"; private static final int DEFAULT_PREFETCH_COUNT = 1; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final Object connectionLock = new Object(); private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class); private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer(); private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); private ClientOptions clientOptions; private Configuration configuration; private ServiceBusConnectionProcessor sharedConnection; private String connectionStringEntityName; private TokenCredential credentials; private String fullyQualifiedNamespace; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport = AmqpTransportType.AMQP; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType */ public ServiceBusClientBuilder() { } /** * Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of * certain properties, as well as support the addition of custom header information. Refer to the * {@link ClientOptions} documentation for more information. * * @param clientOptions to be set on the client. * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the connection string for a Service Bus namespace or a specific Service Bus resource. * * @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential; try { tokenCredential = getTokenCredential(properties); } catch (Exception e) { throw logger.logExceptionAsError( new AzureException("Could not create the ServiceBusSharedKeyCredential.", e)); } this.fullyQualifiedNamespace = properties.getEndpoint().getHost(); if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) { logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath()); this.connectionStringEntityName = properties.getEntityPath(); } return credential(properties.getEndpoint().getHost(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY); } else { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure Service Bus clients. Use * {@link Configuration * * @param configuration The configuration store used to configure Service Bus clients. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the credential for the Service Bus resource. * * @param fullyQualifiedNamespace for the Service Bus. * @param credential {@link TokenCredential} to be used for authentication. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the retry options for Service Bus clients. If not specified, the default retry options are used. * * @param retryOptions The retry options to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the scheduler to use. * * @param scheduler Scheduler to be used. * * @return The updated {@link ServiceBusClientBuilder} object. */ ServiceBusClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link * AmqpTransportType * * @param transportType The transport type to use. * * @return The updated {@link ServiceBusClientBuilder} object. */ public ServiceBusClientBuilder transportType(AmqpTransportType transportType) { this.transport = transportType; return this; } /** * A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders. * * @return A new instance of {@link ServiceBusSenderClientBuilder}. */ public ServiceBusSenderClientBuilder sender() { return new ServiceBusSenderClientBuilder(); } /** * A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message consumers. * * @return A new instance of {@link ServiceBusReceiverClientBuilder}. */ public ServiceBusReceiverClientBuilder receiver() { return new ServiceBusReceiverClientBuilder(); } /** * A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service * Bus message consumers. * * @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}. */ public ServiceBusSessionReceiverClientBuilder sessionReceiver() { return new ServiceBusSessionReceiverClientBuilder(); } /** * Called when a child client is closed. Disposes of the shared connection if there are no more clients. */ void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection [{}].", sharedConnection); if (sharedConnection != null) { sharedConnection.dispose(); sharedConnection = null; } else { logger.warning("Shared ServiceBusConnectionProcessor was already disposed."); } } } private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } synchronized (connectionLock) { if (sharedConnection == null) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> { final String connectionId = StringUtil.getRandomString("MF"); return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId, connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer, product, clientVersion); }).repeat(); sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry())); } } final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" return sharedConnection; } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } } private static boolean isNullOrEmpty(String item) { return item == null || item.isEmpty(); } private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName, String topicName, String queueName) { final boolean hasTopicName = !isNullOrEmpty(topicName); final boolean hasQueueName = !isNullOrEmpty(queueName); final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName); final MessagingEntityType entityType; if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) { throw logger.logExceptionAsError(new IllegalStateException( "Cannot build client without setting either a queueName or topicName.")); } else if (hasQueueName && hasTopicName) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName))); } else if (hasQueueName) { if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "queueName (%s) is different than the connectionString's EntityPath (%s).", queueName, connectionStringEntityName))); } entityType = MessagingEntityType.QUEUE; } else if (hasTopicName) { if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) is different than the connectionString's EntityPath (%s).", topicName, connectionStringEntityName))); } entityType = MessagingEntityType.SUBSCRIPTION; } else { entityType = MessagingEntityType.UNKNOWN; } return entityType; } private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName, String topicName, String subscriptionName, SubQueue subQueue) { String entityPath; switch (entityType) { case QUEUE: entityPath = queueName; break; case SUBSCRIPTION: if (isNullOrEmpty(subscriptionName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) must have a subscriptionName associated with it.", topicName))); } entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName, subscriptionName); break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } if (subQueue == null) { return entityPath; } switch (subQueue) { case NONE: break; case TRANSFER_DEAD_LETTER_QUEUE: entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX; break; case DEAD_LETTER_QUEUE: entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX; break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: " + subQueue)); } return entityPath; } /** * Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages * to Service Bus. * * @see ServiceBusSenderAsyncClient * @see ServiceBusSenderClient */ @ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class}) public final class ServiceBusSenderClientBuilder { private String queueName; private String topicName; private String viaQueueName; private String viaTopicName; private ServiceBusSenderClientBuilder() { } /** * Sets the name of the Service Bus queue to publish messages to. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSenderClientBuilder} object. */ public ServiceBusSenderClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the name of the initial destination Service Bus queue to publish messages to. * * @param viaQueueName The initial destination of the message. * * @return The modified {@link ServiceBusSenderClientBuilder} object. * * @see <a href="https: */ public ServiceBusSenderClientBuilder viaQueueName(String viaQueueName) { this.viaQueueName = viaQueueName; return this; } /** * Sets the name of the initial destination Service Bus topic to publish messages to. * * @param viaTopicName The initial destination of the message. * * @return The modified {@link ServiceBusSenderClientBuilder} object. * * @see <a href="https: */ public ServiceBusSenderClientBuilder viaTopicName(String viaTopicName) { this.viaTopicName = viaTopicName; return this; } /** * Sets the name of the Service Bus topic to publish messages to. * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSenderClientBuilder} object. */ public ServiceBusSenderClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link * ServiceBusMessage} to a Service Bus queue or topic. * * @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * {@link * @throws IllegalArgumentException if the entity type is not a queue or a topic. */ public ServiceBusSenderAsyncClient buildAsyncClient() { final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); if (!CoreUtils.isNullOrEmpty(viaQueueName) && entityType == MessagingEntityType.SUBSCRIPTION) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "(%s), Via queue feature work only with a queue.", viaQueueName))); } else if (!CoreUtils.isNullOrEmpty(viaTopicName) && entityType == MessagingEntityType.QUEUE) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "(%s), Via topic feature work only with a topic.", viaTopicName))); } final String entityName; final String viaEntityName = !CoreUtils.isNullOrEmpty(viaQueueName) ? viaQueueName : viaTopicName; switch (entityType) { case QUEUE: entityName = queueName; break; case SUBSCRIPTION: entityName = topicName; break; case UNKNOWN: entityName = connectionStringEntityName; break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, viaEntityName); } /** * Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage} * to a Service Bus queue or topic. * * @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * @throws IllegalArgumentException if the entity type is not a queue or a topic. */ public ServiceBusSenderClient buildClient() { return new ServiceBusSenderClient(buildAsyncClient(), retryOptions.getTryTimeout()); } } /** * Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume * messages from a <b>session aware</b> Service Bus entity. * * @see ServiceBusReceiverAsyncClient * @see ServiceBusReceiverClient */ @ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class}) public final class ServiceBusSessionReceiverClientBuilder { private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private ServiceBusSessionReceiverClientBuilder() { } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading * {@link ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); validateAndThrow(prefetchCount); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); if (CoreUtils.isNullOrEmpty(sessionId)) { final UnnamedSessionManager sessionManager = new UnnamedSessionManager(entityPath, entityType, connectionProcessor, connectionProcessor.getRetryOptions().getTryTimeout(), tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); } else { return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading * {@link ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(), retryOptions.getTryTimeout()); } /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } } /** * Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume * messages from Service Bus. * * @see ServiceBusReceiverAsyncClient * @see ServiceBusReceiverClient */ @ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class}) public final class ServiceBusReceiverClientBuilder { private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private SubQueue subQueue; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String subscriptionName; private String topicName; private ServiceBusReceiverClientBuilder() { } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the type of the {@link SubQueue} to connect to. * * @param subQueue The type of the sub queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) { this.subQueue = subQueue; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage * messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, subQueue); validateAndThrow(prefetchCount); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } /** * Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages} * from a specific queue or topic. * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(), retryOptions.getTryTimeout()); } } private void validateAndThrow(int prefetchCount) { if (prefetchCount < 1) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "prefetchCount (%s) cannot be less than 1.", prefetchCount))); } } }
Just to double-check my understanding is correct - instead of changing the place where we were Parsing the Double you decided to normalize the locale here because for all other content where we parse floating point numbers the content is created by our backend and we own the locale/formatting, correct?
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(targetRange.getId(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); BridgeInternal.putQueryMetricsIntoMap(pageResult, targetRange.getId(), qm); } }
QueryMetricsConstants.RequestCharge,
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(targetRange.getId(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); BridgeInternal.putQueryMetricsIntoMap(pageResult, targetRange.getId(), qm); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; PartitionKeyRange sourcePartitionKeyRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourcePartitionKeyRange = DocumentProducer.this.targetRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, PartitionKeyRange pkr) { this.pageResult = pageResult; this.sourcePartitionKeyRange = pkr; populatePartitionedQueryMetrics(); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; PartitionKeyRange sourcePartitionKeyRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourcePartitionKeyRange = DocumentProducer.this.targetRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, PartitionKeyRange pkr) { this.pageResult = pageResult; this.sourcePartitionKeyRange = pkr; populatePartitionedQueryMetrics(); } }
Thats correct Fabian
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(targetRange.getId(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); BridgeInternal.putQueryMetricsIntoMap(pageResult, targetRange.getId(), qm); } }
QueryMetricsConstants.RequestCharge,
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(targetRange.getId(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); BridgeInternal.putQueryMetricsIntoMap(pageResult, targetRange.getId(), qm); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; PartitionKeyRange sourcePartitionKeyRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourcePartitionKeyRange = DocumentProducer.this.targetRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, PartitionKeyRange pkr) { this.pageResult = pageResult; this.sourcePartitionKeyRange = pkr; populatePartitionedQueryMetrics(); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; PartitionKeyRange sourcePartitionKeyRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourcePartitionKeyRange = DocumentProducer.this.targetRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, PartitionKeyRange pkr) { this.pageResult = pageResult; this.sourcePartitionKeyRange = pkr; populatePartitionedQueryMetrics(); } }
Is this the only version that will be used for getting a token? If there are more versions available for this I would prefer us to use an expandable enum in future releases.
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
.append("?api-version=2017-09-01")
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
nit; If we already have the value of `certificateBundle.getCer()` in `certificateString` we can use the variable here. ```suggestion new ByteArrayInputStream(Base64.getDecoder().decode(certificateString)) ```
public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; }
new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer()))
public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; } }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; } }
I'm not entirely familiar with the KeyStore class, is it possible this can throw a `NoSuchElementException` in this case?
public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; }
alias = keyStore.aliases().nextElement();
public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ }
Certificates downloaded from Key Vault through the get secret API might be in PKCS12 or PEM format. These can be differentiated by the by the `contentType` of the secret bundle.
public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; }
KeyStore keyStore = KeyStore.getInstance("PKCS12");
public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ }
I believe the resource string will need to be url encoded no?
private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; }
.append(RESOURCE_FRAGMENT).append(resource);
private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; } /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; } /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ }
I believe the resource string will need to be url encoded no?
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
.append(RESOURCE_FRAGMENT).append(resource);
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
Should we also log a warning if the alias turns out to be null in the end?
public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseClientAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose client alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseClientAlias", alias); return alias; }
LOGGER.log(WARNING, "Unable to choose client alias", kse);
public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseClientAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose client alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseClientAlias", alias); return alias; }
class KeyVaultKeyManager extends X509ExtendedKeyManager { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManager.class.getName()); /** * Stores the keystore. */ private final KeyStore keystore; /** * Stores the password. */ private final char[] password; /** * Constructor. * * @param keystore the keystore. * @param password the password. */ public KeyVaultKeyManager(KeyStore keystore, char[] password) { LOGGER.entering("KeyVaultKeyManager", "<init>", new Object[] { keystore, password }); this.keystore = keystore; this.password = password; } @Override @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseServerAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose server alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseServerAlias", alias); return alias; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}, {1}", new Object[] { keyType, issuers }); String[] aliases = null; try { aliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get client aliases", kse); } LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}", aliases); return aliases; } @Override public X509Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultKeyManager", "getCertificateChain", alias); List<X509Certificate> chain = new ArrayList<>(); try { Certificate[] keystoreChain = keystore.getCertificateChain(alias); if (keystoreChain.length > 0) { for (Certificate certificate : keystoreChain) { if (certificate instanceof X509Certificate) { chain.add((X509Certificate) certificate); } } } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get certificate chain for alias: " + alias, kse); } LOGGER.exiting("KeyVaultKeyManager", "getCertificateChain", chain); return chain.toArray(new X509Certificate[0]); } @Override public PrivateKey getPrivateKey(String alias) { LOGGER.entering("KeyVaultKeyManager", "getPrivateKey", alias); PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(alias, password); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { LOGGER.log(WARNING, "Unable to get private key for alias: " + alias, ex); } LOGGER.exiting("KeyVaultKeyManager", "getPrivateKey", privateKey); return privateKey; } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { LOGGER.entering("KeyVaultKeyManager", "getServerAliases", new Object[] { keyType, issuers }); String[] serverAliases = new String[0]; try { serverAliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get server aliases", kse); } LOGGER.exiting("KeyVaultKeyManager", "getServerAliases", serverAliases); return serverAliases; } }
class KeyVaultKeyManager extends X509ExtendedKeyManager { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManager.class.getName()); /** * Stores the keystore. */ private final KeyStore keystore; /** * Stores the password. */ private final char[] password; /** * Constructor. * * @param keystore the keystore. * @param password the password. */ public KeyVaultKeyManager(KeyStore keystore, char[] password) { LOGGER.entering("KeyVaultKeyManager", "<init>", new Object[] { keystore, password }); this.keystore = keystore; this.password = password; } @Override @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseServerAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose server alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseServerAlias", alias); return alias; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}, {1}", new Object[] { keyType, issuers }); String[] aliases = null; try { aliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get client aliases", kse); } LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}", aliases); return aliases; } @Override public X509Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultKeyManager", "getCertificateChain", alias); List<X509Certificate> chain = new ArrayList<>(); try { Certificate[] keystoreChain = keystore.getCertificateChain(alias); if (keystoreChain.length > 0) { for (Certificate certificate : keystoreChain) { if (certificate instanceof X509Certificate) { chain.add((X509Certificate) certificate); } } } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get certificate chain for alias: " + alias, kse); } LOGGER.exiting("KeyVaultKeyManager", "getCertificateChain", chain); return chain.toArray(new X509Certificate[0]); } @Override public PrivateKey getPrivateKey(String alias) { LOGGER.entering("KeyVaultKeyManager", "getPrivateKey", alias); PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(alias, password); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { LOGGER.log(WARNING, "Unable to get private key for alias: " + alias, ex); } LOGGER.exiting("KeyVaultKeyManager", "getPrivateKey", privateKey); return privateKey; } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { LOGGER.entering("KeyVaultKeyManager", "getServerAliases", new Object[] { keyType, issuers }); String[] serverAliases = new String[0]; try { serverAliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get server aliases", kse); } LOGGER.exiting("KeyVaultKeyManager", "getServerAliases", serverAliases); return serverAliases; } }
We don't need to check if `keystoreChain` is not empty if we are using a foreach loop.
public X509Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultKeyManager", "getCertificateChain", alias); List<X509Certificate> chain = new ArrayList<>(); try { Certificate[] keystoreChain = keystore.getCertificateChain(alias); if (keystoreChain.length > 0) { for (Certificate certificate : keystoreChain) { if (certificate instanceof X509Certificate) { chain.add((X509Certificate) certificate); } } } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get certificate chain for alias: " + alias, kse); } LOGGER.exiting("KeyVaultKeyManager", "getCertificateChain", chain); return chain.toArray(new X509Certificate[0]); }
for (Certificate certificate : keystoreChain) {
public X509Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultKeyManager", "getCertificateChain", alias); List<X509Certificate> chain = new ArrayList<>(); try { Certificate[] keystoreChain = keystore.getCertificateChain(alias); if (keystoreChain.length > 0) { for (Certificate certificate : keystoreChain) { if (certificate instanceof X509Certificate) { chain.add((X509Certificate) certificate); } } } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get certificate chain for alias: " + alias, kse); } LOGGER.exiting("KeyVaultKeyManager", "getCertificateChain", chain); return chain.toArray(new X509Certificate[0]); }
class KeyVaultKeyManager extends X509ExtendedKeyManager { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManager.class.getName()); /** * Stores the keystore. */ private final KeyStore keystore; /** * Stores the password. */ private final char[] password; /** * Constructor. * * @param keystore the keystore. * @param password the password. */ public KeyVaultKeyManager(KeyStore keystore, char[] password) { LOGGER.entering("KeyVaultKeyManager", "<init>", new Object[] { keystore, password }); this.keystore = keystore; this.password = password; } @Override public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseClientAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose client alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseClientAlias", alias); return alias; } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseServerAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose server alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseServerAlias", alias); return alias; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}, {1}", new Object[] { keyType, issuers }); String[] aliases = null; try { aliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get client aliases", kse); } LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}", aliases); return aliases; } @Override @Override public PrivateKey getPrivateKey(String alias) { LOGGER.entering("KeyVaultKeyManager", "getPrivateKey", alias); PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(alias, password); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { LOGGER.log(WARNING, "Unable to get private key for alias: " + alias, ex); } LOGGER.exiting("KeyVaultKeyManager", "getPrivateKey", privateKey); return privateKey; } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { LOGGER.entering("KeyVaultKeyManager", "getServerAliases", new Object[] { keyType, issuers }); String[] serverAliases = new String[0]; try { serverAliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get server aliases", kse); } LOGGER.exiting("KeyVaultKeyManager", "getServerAliases", serverAliases); return serverAliases; } }
class KeyVaultKeyManager extends X509ExtendedKeyManager { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManager.class.getName()); /** * Stores the keystore. */ private final KeyStore keystore; /** * Stores the password. */ private final char[] password; /** * Constructor. * * @param keystore the keystore. * @param password the password. */ public KeyVaultKeyManager(KeyStore keystore, char[] password) { LOGGER.entering("KeyVaultKeyManager", "<init>", new Object[] { keystore, password }); this.keystore = keystore; this.password = password; } @Override public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseClientAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose client alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseClientAlias", alias); return alias; } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseServerAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose server alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseServerAlias", alias); return alias; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}, {1}", new Object[] { keyType, issuers }); String[] aliases = null; try { aliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get client aliases", kse); } LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}", aliases); return aliases; } @Override @Override public PrivateKey getPrivateKey(String alias) { LOGGER.entering("KeyVaultKeyManager", "getPrivateKey", alias); PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(alias, password); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { LOGGER.log(WARNING, "Unable to get private key for alias: " + alias, ex); } LOGGER.exiting("KeyVaultKeyManager", "getPrivateKey", privateKey); return privateKey; } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { LOGGER.entering("KeyVaultKeyManager", "getServerAliases", new Object[] { keyType, issuers }); String[] serverAliases = new String[0]; try { serverAliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get server aliases", kse); } LOGGER.exiting("KeyVaultKeyManager", "getServerAliases", serverAliases); return serverAliases; } }
There's a newer 2019 API version available, which uses IDENTITY_ENDPOINT and IDENTITY_HEADER env vars.
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
.append("?api-version=2017-09-01")
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
with 2017 API version, I believe the expiry time comes in different formats on Windows and Linux based App Services, is that being handled here ?
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class);
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
This URL won't work on all of the other Azure Platforms, for e.g. Azure Service Fabric
private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; }
url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL)
private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; } /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; } /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ }
I'm not familiar with JCA but I wonder why these methods for keys are empty but we have things like `engineIsKeyEntry` where we call `engineIsCertificateEntry` inside. How is `engineIsKeyEntry` different that it needs an implementation, is it 100% expected to be used and the other methods are not? Are there scenarios where things like `engineSetKeyEntry` might need an implementation?
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { }
}
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
`InputStream` and `BufferedReader` must be closed after use in a `finally` block to avoid leaks. It is even more convenient to use try-with-resources statements. ```suggestion try (InputStream in = getClass().getResourceAsStream(path)) { if (in != null) { try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) { String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } } } return filenames.toArray(new String[0]); ```
private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); }
return filenames.toArray(new String[0]);
private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
Use a try-with-resources block to ensure this is closed after use. ```suggestion byte[] bytes; try (ByteArrayOutputStream byteOutput = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } bytes = byteOutput.toByteArray(); } return bytes; ```
private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); }
return byteOutput.toByteArray();
private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
Adding `null` check in case bytes could not be read considering my previous comment. ```suggestion byte[] bytes = readAllBytes(inputStream); if (bytes != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[]{alias, filename}); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } else { LOGGER.log(WARNING, "Unable to side-load certificate"); } ```
private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } }
}
private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ }
Can we use a logger in instances like these like in the rest of the classes in this package?
public KeyVaultTrustManager(KeyStore keyStore) { this.keyStore = keyStore; if (this.keyStore == null) { try { this.keyStore = KeyStore.getInstance("AzureKeyVault"); this.keyStore.load(null, null); } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException ex) { ex.printStackTrace(); } } try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "SunJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } if (defaultTrustManager == null) { try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "IbmJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } } }
ex.printStackTrace();
public KeyVaultTrustManager(KeyStore keyStore) { this.keyStore = keyStore; if (this.keyStore == null) { try { this.keyStore = KeyStore.getInstance("AzureKeyVault"); this.keyStore.load(null, null); } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException ex) { ex.printStackTrace(); } } try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "SunJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } if (defaultTrustManager == null) { try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "IbmJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } } }
class KeyVaultTrustManager extends X509ExtendedTrustManager implements X509TrustManager { /** * Stores the default trust manager. */ private X509TrustManager defaultTrustManager; /** * Stores the keystore. */ private KeyStore keyStore; /** * Constructor. * * @param keyStore the keystore. */ @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkServerTrusted(chain, authType); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkServerTrusted(chain, authType); } }
class KeyVaultTrustManager extends X509ExtendedTrustManager implements X509TrustManager { /** * Stores the default trust manager. */ private X509TrustManager defaultTrustManager; /** * Stores the keystore. */ private KeyStore keyStore; /** * Constructor. * * @param keyStore the keystore. */ @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkServerTrusted(chain, authType); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkServerTrusted(chain, authType); } }
Would returning an empty array cause any bugs down the line?
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
class KeyVaultTrustManager extends X509ExtendedTrustManager implements X509TrustManager { /** * Stores the default trust manager. */ private X509TrustManager defaultTrustManager; /** * Stores the keystore. */ private KeyStore keyStore; /** * Constructor. * * @param keyStore the keystore. */ public KeyVaultTrustManager(KeyStore keyStore) { this.keyStore = keyStore; if (this.keyStore == null) { try { this.keyStore = KeyStore.getInstance("AzureKeyVault"); this.keyStore.load(null, null); } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException ex) { ex.printStackTrace(); } } try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "SunJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } if (defaultTrustManager == null) { try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "IbmJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } } } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkServerTrusted(chain, authType); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkServerTrusted(chain, authType); } }
class KeyVaultTrustManager extends X509ExtendedTrustManager implements X509TrustManager { /** * Stores the default trust manager. */ private X509TrustManager defaultTrustManager; /** * Stores the keystore. */ private KeyStore keyStore; /** * Constructor. * * @param keyStore the keystore. */ public KeyVaultTrustManager(KeyStore keyStore) { this.keyStore = keyStore; if (this.keyStore == null) { try { this.keyStore = KeyStore.getInstance("AzureKeyVault"); this.keyStore.load(null, null); } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException ex) { ex.printStackTrace(); } } try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "SunJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } if (defaultTrustManager == null) { try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "IbmJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } } } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkServerTrusted(chain, authType); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkServerTrusted(chain, authType); } }
Can we name these `getKeyProperties` and `setKeyProperties`?
public void setKey_props(KeyProperties keyProperties) { this.keyProperties = keyProperties; }
}
public void setKey_props(KeyProperties keyProperties) { this.keyProperties = keyProperties; }
class CertificatePolicy implements Serializable { /** * Stores the key properties. */ private KeyProperties keyProperties; /** * Get the key properties. * * @return the key properties. */ public KeyProperties getKey_props() { return keyProperties; } /** * Set the key properties. * * @param keyProperties the key properties. */ }
class CertificatePolicy implements Serializable { /** * Stores the key properties. */ private KeyProperties keyProperties; /** * Get the key properties. * * @return the key properties. */ public KeyProperties getKey_props() { return keyProperties; } /** * Set the key properties. * * @param keyProperties the key properties. */ }
Can we name these `getAccessToken` and `setAccessToken`? ```suggestion public String getAccessToken() { return accessToken; } /** * Set the access token. * * @param accessToken the access token. */ public void setAccessToken(String accessToken) { this.accessToken = accessToken; } ```
public void setAccess_token(String accessToken) { this.access_token = accessToken; }
}
public void setAccess_token(String accessToken) { this.access_token = accessToken; }
class OAuthToken implements Serializable { /** * Stores the access token. */ private String access_token; /** * Get the access token. * * @return the access token. */ public String getAccess_token() { return access_token; } /** * Set the access token. * * @param accessToken the access token. */ }
class OAuthToken implements Serializable { /** * Stores the access token. */ private String access_token; /** * Get the access token. * * @return the access token. */ public String getAccess_token() { return access_token; } /** * Set the access token. * * @param accessToken the access token. */ }
The KeyVaultClient code passes in a url encoded version so nothing further needs to be done
private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; }
.append(RESOURCE_FRAGMENT).append(resource);
private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; } /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; } /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ }
The KeyVaultClient code passes in a url encoded version so nothing further needs to be done
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
.append(RESOURCE_FRAGMENT).append(resource);
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
In this particular case because we create a new Keystore and we load a specifically with just one certificate `NoSuchElementException' would not be thrown, because if loading failed it would have triggered the catch block.
public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; }
alias = keyStore.aliases().nextElement();
public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ }
Fixed
public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; }
new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer()))
public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer())) ); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; } }
class KeyVaultClient extends DelegateRestClient { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the API version postfix. */ private static final String API_VERSION_POSTFIX = "?api-version=7.1"; /** * Stores the KeyVault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private String tenantId; /** * Stores the client ID. */ private String clientId; /** * Stores the client secret. */ private String clientSecret; /** * Constructor. * * @param keyVaultUri the KeyVault URI. */ KeyVaultClient(String keyVaultUri) { super(RestClientFactory.createClient()); LOGGER.log(INFO, "Using KeyVault: {0}", keyVaultUri); if (!keyVaultUri.endsWith("/")) { keyVaultUri = keyVaultUri + "/"; } this.keyVaultUri = keyVaultUri; } /** * Constructor. * * @param keyVaultUri the KeyVault URI. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. */ KeyVaultClient(final String keyVaultUri, final String tenantId, final String clientId, final String clientSecret) { this(keyVaultUri); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Get the access token. * * @return the access token. */ private String getAccessToken() { LOGGER.entering("KeyVaultClient", "getAccessToken"); String accessToken = null; try { AuthClient authClient = new AuthClient(); String resource = URLEncoder.encode("https: if (tenantId != null && clientId != null && clientSecret != null) { accessToken = authClient.getAccessToken(resource, tenantId, clientId, clientSecret); } else { accessToken = authClient.getAccessToken(resource); } } catch (UnsupportedEncodingException uee) { LOGGER.log(WARNING, "Unsupported encoding", uee); } LOGGER.exiting("KeyVaultClient", "getAccessToken", accessToken); return accessToken; } /** * Get the list of aliases. * * @return the list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX); String response = get(url, headers); CertificateListResult certificateListResult = null; if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); certificateListResult = (CertificateListResult) converter.fromJson(response, CertificateListResult.class); } if (certificateListResult != null && certificateListResult.getValue().size() > 0) { for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } return result; } /** * Get the certificate bundle. * * @param alias the alias. * @return the certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX); String response = get(url, headers); if (response != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); result = (CertificateBundle) converter.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias the alias. * @return the certificate, or null if not found. */ /** * Get the key. * * @param alias the alias. * @param password the password. * @return the key. */ public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); Key key = null; CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKey_props) .map(KeyProperties::isExportable) .orElse(false); if (isExportable) { String certificateSecretUri = certificateBundle.getSid(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); SecretBundle secretBundle = (SecretBundle) converter.fromJson(body, SecretBundle.class); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray() ); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } } else { } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; } }
Fixed
public X509Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultKeyManager", "getCertificateChain", alias); List<X509Certificate> chain = new ArrayList<>(); try { Certificate[] keystoreChain = keystore.getCertificateChain(alias); if (keystoreChain.length > 0) { for (Certificate certificate : keystoreChain) { if (certificate instanceof X509Certificate) { chain.add((X509Certificate) certificate); } } } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get certificate chain for alias: " + alias, kse); } LOGGER.exiting("KeyVaultKeyManager", "getCertificateChain", chain); return chain.toArray(new X509Certificate[0]); }
for (Certificate certificate : keystoreChain) {
public X509Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultKeyManager", "getCertificateChain", alias); List<X509Certificate> chain = new ArrayList<>(); try { Certificate[] keystoreChain = keystore.getCertificateChain(alias); if (keystoreChain.length > 0) { for (Certificate certificate : keystoreChain) { if (certificate instanceof X509Certificate) { chain.add((X509Certificate) certificate); } } } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get certificate chain for alias: " + alias, kse); } LOGGER.exiting("KeyVaultKeyManager", "getCertificateChain", chain); return chain.toArray(new X509Certificate[0]); }
class KeyVaultKeyManager extends X509ExtendedKeyManager { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManager.class.getName()); /** * Stores the keystore. */ private final KeyStore keystore; /** * Stores the password. */ private final char[] password; /** * Constructor. * * @param keystore the keystore. * @param password the password. */ public KeyVaultKeyManager(KeyStore keystore, char[] password) { LOGGER.entering("KeyVaultKeyManager", "<init>", new Object[] { keystore, password }); this.keystore = keystore; this.password = password; } @Override public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseClientAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose client alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseClientAlias", alias); return alias; } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseServerAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose server alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseServerAlias", alias); return alias; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}, {1}", new Object[] { keyType, issuers }); String[] aliases = null; try { aliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get client aliases", kse); } LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}", aliases); return aliases; } @Override @Override public PrivateKey getPrivateKey(String alias) { LOGGER.entering("KeyVaultKeyManager", "getPrivateKey", alias); PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(alias, password); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { LOGGER.log(WARNING, "Unable to get private key for alias: " + alias, ex); } LOGGER.exiting("KeyVaultKeyManager", "getPrivateKey", privateKey); return privateKey; } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { LOGGER.entering("KeyVaultKeyManager", "getServerAliases", new Object[] { keyType, issuers }); String[] serverAliases = new String[0]; try { serverAliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get server aliases", kse); } LOGGER.exiting("KeyVaultKeyManager", "getServerAliases", serverAliases); return serverAliases; } }
class KeyVaultKeyManager extends X509ExtendedKeyManager { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManager.class.getName()); /** * Stores the keystore. */ private final KeyStore keystore; /** * Stores the password. */ private final char[] password; /** * Constructor. * * @param keystore the keystore. * @param password the password. */ public KeyVaultKeyManager(KeyStore keystore, char[] password) { LOGGER.entering("KeyVaultKeyManager", "<init>", new Object[] { keystore, password }); this.keystore = keystore; this.password = password; } @Override public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseClientAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose client alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseClientAlias", alias); return alias; } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseServerAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose server alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseServerAlias", alias); return alias; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}, {1}", new Object[] { keyType, issuers }); String[] aliases = null; try { aliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get client aliases", kse); } LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}", aliases); return aliases; } @Override @Override public PrivateKey getPrivateKey(String alias) { LOGGER.entering("KeyVaultKeyManager", "getPrivateKey", alias); PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(alias, password); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { LOGGER.log(WARNING, "Unable to get private key for alias: " + alias, ex); } LOGGER.exiting("KeyVaultKeyManager", "getPrivateKey", privateKey); return privateKey; } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { LOGGER.entering("KeyVaultKeyManager", "getServerAliases", new Object[] { keyType, issuers }); String[] serverAliases = new String[0]; try { serverAliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get server aliases", kse); } LOGGER.exiting("KeyVaultKeyManager", "getServerAliases", serverAliases); return serverAliases; } }
Set engineSet methods do not get an implementation here because the Azure Key Vault KeyStore is a read-only KeyStore
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { }
}
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
No as that would cause the application potentially to be very chatty. If the customer would need to know if it is indeed returning `null` they can change the logging level.
public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseClientAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose client alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseClientAlias", alias); return alias; }
LOGGER.log(WARNING, "Unable to choose client alias", kse);
public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseClientAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose client alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseClientAlias", alias); return alias; }
class KeyVaultKeyManager extends X509ExtendedKeyManager { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManager.class.getName()); /** * Stores the keystore. */ private final KeyStore keystore; /** * Stores the password. */ private final char[] password; /** * Constructor. * * @param keystore the keystore. * @param password the password. */ public KeyVaultKeyManager(KeyStore keystore, char[] password) { LOGGER.entering("KeyVaultKeyManager", "<init>", new Object[] { keystore, password }); this.keystore = keystore; this.password = password; } @Override @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseServerAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose server alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseServerAlias", alias); return alias; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}, {1}", new Object[] { keyType, issuers }); String[] aliases = null; try { aliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get client aliases", kse); } LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}", aliases); return aliases; } @Override public X509Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultKeyManager", "getCertificateChain", alias); List<X509Certificate> chain = new ArrayList<>(); try { Certificate[] keystoreChain = keystore.getCertificateChain(alias); if (keystoreChain.length > 0) { for (Certificate certificate : keystoreChain) { if (certificate instanceof X509Certificate) { chain.add((X509Certificate) certificate); } } } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get certificate chain for alias: " + alias, kse); } LOGGER.exiting("KeyVaultKeyManager", "getCertificateChain", chain); return chain.toArray(new X509Certificate[0]); } @Override public PrivateKey getPrivateKey(String alias) { LOGGER.entering("KeyVaultKeyManager", "getPrivateKey", alias); PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(alias, password); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { LOGGER.log(WARNING, "Unable to get private key for alias: " + alias, ex); } LOGGER.exiting("KeyVaultKeyManager", "getPrivateKey", privateKey); return privateKey; } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { LOGGER.entering("KeyVaultKeyManager", "getServerAliases", new Object[] { keyType, issuers }); String[] serverAliases = new String[0]; try { serverAliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get server aliases", kse); } LOGGER.exiting("KeyVaultKeyManager", "getServerAliases", serverAliases); return serverAliases; } }
class KeyVaultKeyManager extends X509ExtendedKeyManager { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyManager.class.getName()); /** * Stores the keystore. */ private final KeyStore keystore; /** * Stores the password. */ private final char[] password; /** * Constructor. * * @param keystore the keystore. * @param password the password. */ public KeyVaultKeyManager(KeyStore keystore, char[] password) { LOGGER.entering("KeyVaultKeyManager", "<init>", new Object[] { keystore, password }); this.keystore = keystore; this.password = password; } @Override @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { LOGGER.entering( "KeyVaultKeyManager", "chooseServerAlias", new Object[] { keyType, issuers, socket } ); String alias = null; try { /* * If we only have one alias and the keystore type is not 'AzureKeyVault' * return that alias as a match. */ if (!keystore.getProvider().getName().equals("AzureKeyVault") && keystore.size() == 1) { alias = keystore.aliases().nextElement(); } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to choose server alias", kse); } LOGGER.exiting("KeyVaultKeyManager", "chooseServerAlias", alias); return alias; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}, {1}", new Object[] { keyType, issuers }); String[] aliases = null; try { aliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get client aliases", kse); } LOGGER.log(INFO, "KeyVaultKeyManager.getClientAliases: {0}", aliases); return aliases; } @Override public X509Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultKeyManager", "getCertificateChain", alias); List<X509Certificate> chain = new ArrayList<>(); try { Certificate[] keystoreChain = keystore.getCertificateChain(alias); if (keystoreChain.length > 0) { for (Certificate certificate : keystoreChain) { if (certificate instanceof X509Certificate) { chain.add((X509Certificate) certificate); } } } } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get certificate chain for alias: " + alias, kse); } LOGGER.exiting("KeyVaultKeyManager", "getCertificateChain", chain); return chain.toArray(new X509Certificate[0]); } @Override public PrivateKey getPrivateKey(String alias) { LOGGER.entering("KeyVaultKeyManager", "getPrivateKey", alias); PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(alias, password); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { LOGGER.log(WARNING, "Unable to get private key for alias: " + alias, ex); } LOGGER.exiting("KeyVaultKeyManager", "getPrivateKey", privateKey); return privateKey; } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { LOGGER.entering("KeyVaultKeyManager", "getServerAliases", new Object[] { keyType, issuers }); String[] serverAliases = new String[0]; try { serverAliases = Collections.list(keystore.aliases()).toArray(new String[0]); } catch (KeyStoreException kse) { LOGGER.log(WARNING, "Unable to get server aliases", kse); } LOGGER.exiting("KeyVaultKeyManager", "getServerAliases", serverAliases); return serverAliases; } }
Fixed
private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); }
return filenames.toArray(new String[0]);
private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
Fixed
private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); }
return byteOutput.toByteArray();
private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ /** * Side-load certificate from classpath. */ private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } } }
Not needed as it will either return a byte-array (potentially empty) or throw an IOException
private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } }
}
private void sideLoad() { try { String[] filenames = getFilenames("/keyvault"); if (filenames.length > 0) { for (String filename : filenames) { try (InputStream inputStream = getClass().getResourceAsStream("/keyvault/" + filename)) { String alias = filename; if (alias != null) { if (alias.lastIndexOf('.') != -1) { alias = alias.substring(0, alias.lastIndexOf('.')); } byte[] bytes = readAllBytes(inputStream); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(bytes)); engineSetCertificateEntry(alias, certificate); LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}", new Object[] { alias, filename }); } catch (CertificateException e) { LOGGER.log(WARNING, "Unable to side-load certificate", e); } } } } } } catch (IOException ioe) { LOGGER.log(WARNING, "Unable to determine certificates to side-load", ioe); } }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the list of aliases. */ private List<String> aliases; /** * Stores the certificates by alias. */ private final HashMap<String, Certificate> certificates = new HashMap<>(); /** * Stores the certificate keys by alias. */ private final HashMap<String, Key> certificateKeys = new HashMap<>(); /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVault; /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> to initialize the keyvault * client. * </p> */ public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenantId"); String clientId = System.getProperty("azure.keyvault.clientId"); String clientSecret = System.getProperty("azure.keyvault.clientSecret"); keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } @Override public Enumeration<String> engineAliases() { if (aliases == null) { aliases = keyVault.getAliases(); } return Collections.enumeration(aliases); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate; if (certificates.containsKey(alias)) { certificate = certificates.get(alias); } else { certificate = keyVault.getCertificate(alias); if (certificate != null) { certificates.put(alias, certificate); if (!aliases.contains(alias)) { aliases.add(alias); } } } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { if (aliases == null) { aliases = keyVault.getAliases(); } for (String candidateAlias : aliases) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return creationDate; } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { Key key; if (certificateKeys.containsKey(alias)) { key = certificateKeys.get(alias); } else { key = keyVault.getKey(alias, password); if (key != null) { certificateKeys.put(alias, key); if (!aliases.contains(alias)) { aliases.add(alias); } } } return key; } @Override public boolean engineIsCertificateEntry(String alias) { if (aliases == null) { aliases = keyVault.getAliases(); } return aliases.contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; keyVault = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } sideLoad(); } @Override public void engineLoad(InputStream stream, char[] password) { sideLoad(); } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (aliases == null) { aliases = keyVault.getAliases(); } if (!aliases.contains(alias)) { aliases.add(alias); certificates.put(alias, certificate); } } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return aliases != null ? aliases.size() : 0; } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } /** * Get the filenames. * * @param path the path. * @return the filenames. * @throws IOException when an I/O error occurs. */ private String[] getFilenames(String path) throws IOException { List<String> filenames = new ArrayList<>(); InputStream in = getClass().getResourceAsStream(path); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); } } return filenames.toArray(new String[0]); } /** * Read all the bytes for a given input stream. * * @param inputStream the input stream. * @return the byte-array. * @throws IOException when an I/O error occurs. */ private byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = inputStream.read(buffer); if (r == -1) { break; } byteOutput.write(buffer, 0, r); } return byteOutput.toByteArray(); } /** * Side-load certificate from classpath. */ }
For the current use cases this is enough. This might change when we implement support for mTLS.
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
class KeyVaultTrustManager extends X509ExtendedTrustManager implements X509TrustManager { /** * Stores the default trust manager. */ private X509TrustManager defaultTrustManager; /** * Stores the keystore. */ private KeyStore keyStore; /** * Constructor. * * @param keyStore the keystore. */ public KeyVaultTrustManager(KeyStore keyStore) { this.keyStore = keyStore; if (this.keyStore == null) { try { this.keyStore = KeyStore.getInstance("AzureKeyVault"); this.keyStore.load(null, null); } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException ex) { ex.printStackTrace(); } } try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "SunJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } if (defaultTrustManager == null) { try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "IbmJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } } } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkServerTrusted(chain, authType); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkServerTrusted(chain, authType); } }
class KeyVaultTrustManager extends X509ExtendedTrustManager implements X509TrustManager { /** * Stores the default trust manager. */ private X509TrustManager defaultTrustManager; /** * Stores the keystore. */ private KeyStore keyStore; /** * Constructor. * * @param keyStore the keystore. */ public KeyVaultTrustManager(KeyStore keyStore) { this.keyStore = keyStore; if (this.keyStore == null) { try { this.keyStore = KeyStore.getInstance("AzureKeyVault"); this.keyStore.load(null, null); } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException ex) { ex.printStackTrace(); } } try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "SunJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } if (defaultTrustManager == null) { try { TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX", "IbmJSSE"); factory.init(keyStore); defaultTrustManager = (X509TrustManager) factory.getTrustManagers()[0]; } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException ex) { ex.printStackTrace(); } } } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { boolean pass = true; /* * Step 1 - see if the default trust manager passes. */ try { defaultTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException ce) { pass = false; } /* * Step 2 - see if the certificate exists in the keystore. */ if (!pass) { String alias = null; try { alias = keyStore.getCertificateAlias(chain[0]); } catch (KeyStoreException kse) { kse.printStackTrace(); } if (alias == null) { throw new CertificateException("Unable to verify in keystore"); } } } @Override @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { checkServerTrusted(chain, authType); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { checkServerTrusted(chain, authType); } }
Fixed
public void setKey_props(KeyProperties keyProperties) { this.keyProperties = keyProperties; }
}
public void setKey_props(KeyProperties keyProperties) { this.keyProperties = keyProperties; }
class CertificatePolicy implements Serializable { /** * Stores the key properties. */ private KeyProperties keyProperties; /** * Get the key properties. * * @return the key properties. */ public KeyProperties getKey_props() { return keyProperties; } /** * Set the key properties. * * @param keyProperties the key properties. */ }
class CertificatePolicy implements Serializable { /** * Stores the key properties. */ private KeyProperties keyProperties; /** * Get the key properties. * * @return the key properties. */ public KeyProperties getKey_props() { return keyProperties; } /** * Set the key properties. * * @param keyProperties the key properties. */ }
This will be indeed the only version as this code is not user configurable. This is by design so we eliminate user error.
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
.append("?api-version=2017-09-01")
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
Fixed
public void setAccess_token(String accessToken) { this.access_token = accessToken; }
}
public void setAccess_token(String accessToken) { this.access_token = accessToken; }
class OAuthToken implements Serializable { /** * Stores the access token. */ private String access_token; /** * Get the access token. * * @return the access token. */ public String getAccess_token() { return access_token; } /** * Set the access token. * * @param accessToken the access token. */ }
class OAuthToken implements Serializable { /** * Stores the access token. */ private String access_token; /** * Get the access token. * * @return the access token. */ public String getAccess_token() { return access_token; } /** * Set the access token. * * @param accessToken the access token. */ }
Hi @g2vinay , I found the following [information ](https://docs.microsoft.com/azure/app-service/overview-managed-identity?tabs=dotnet#using-the-rest-protocol)that when using Linux Consumption, 2017 API version is required. Thus is it a better choice that we remain use of 2017 API version to support more cases? ![image](https://user-images.githubusercontent.com/63028776/111747900-d435d080-88ca-11eb-8a48-397530a2646b.png)
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
.append("?api-version=2017-09-01")
private String getAccessTokenOnAppService(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnAppService", resource); LOGGER.info("Getting access token using managed identity based on MSI_SECRET"); String result = null; StringBuilder url = new StringBuilder(); url.append(System.getenv("MSI_ENDPOINT")) .append("?api-version=2017-09-01") .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); headers.put("Secret", System.getenv("MSI_SECRET")); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result); return result; }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
class AuthClient extends DelegateRestClient { /** * Stores the Client ID fragment. */ private static final String CLIENT_ID_FRAGMENT = "&client_id="; /** * Stores the Client Secret fragment. */ private static final String CLIENT_SECRET_FRAGMENT = "&client_secret="; /** * Stores the Grant Type fragment. */ private static final String GRANT_TYPE_FRAGMENT = "grant_type=client_credentials"; /** * Stores the Resource fragment. */ private static final String RESOURCE_FRAGMENT = "&resource="; /** * Stores the OAuth2 token base URL. */ private static final String OAUTH2_TOKEN_BASE_URL = "https: /** * Stores the OAuth2 token postfix. */ private static final String OAUTH2_TOKEN_POSTFIX = "/oauth2/token"; /** * Stores the OAuth2 managed identity URL. */ private static final String OAUTH2_MANAGED_IDENTITY_TOKEN_URL = "http: /** * Stores our logger. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** * Constructor. * * <p> * The constructor creates a default RestClient. * </p> */ AuthClient() { super(RestClientFactory.createClient()); } /** * Get an access token for a managed identity. * * @param resource the resource. * @return the authorization token. */ public String getAccessToken(String resource) { String result; if (System.getenv("WEBSITE_SITE_NAME") != null && !System.getenv("WEBSITE_SITE_NAME").isEmpty()) { result = getAccessTokenOnAppService(resource); } else { result = getAccessTokenOnOthers(resource); } return result; } /** * Get an access token. * * @param resource the resource. * @param tenantId the tenant ID. * @param clientId the client ID. * @param clientSecret the client secret. * @return the authorization token. */ public String getAccessToken(String resource, String tenantId, String clientId, String clientSecret) { LOGGER.entering("AuthClient", "getAccessToken", new Object[] { resource, tenantId, clientId, clientSecret }); LOGGER.info("Getting access token using client ID / client secret"); String result = null; StringBuilder oauth2Url = new StringBuilder(); oauth2Url.append(OAUTH2_TOKEN_BASE_URL) .append(tenantId) .append(OAUTH2_TOKEN_POSTFIX); StringBuilder requestBody = new StringBuilder(); requestBody.append(GRANT_TYPE_FRAGMENT) .append(CLIENT_ID_FRAGMENT).append(clientId) .append(CLIENT_SECRET_FRAGMENT).append(clientSecret) .append(RESOURCE_FRAGMENT).append(resource); String body = post(oauth2Url.toString(), requestBody.toString(), "application/x-www-form-urlencoded"); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.log(FINER, "Access token: {0}", result); return result; } /** * Get the access token on Azure App Service. * * @param resource the resource. * @return the authorization token. */ /** * Get the authorization token on everything else but Azure App Service. * * @param resource the resource. * @return the authorization token. */ private String getAccessTokenOnOthers(String resource) { LOGGER.entering("AuthClient", "getAccessTokenOnOthers", resource); LOGGER.info("Getting access token using managed identity"); String result = null; StringBuilder url = new StringBuilder(); url.append(OAUTH2_MANAGED_IDENTITY_TOKEN_URL) .append(RESOURCE_FRAGMENT).append(resource); HashMap<String, String> headers = new HashMap<>(); headers.put("Metadata", "true"); String body = get(url.toString(), headers); if (body != null) { JsonConverter converter = JsonConverterFactory.createJsonConverter(); OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class); result = token.getAccess_token(); } LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result); return result; } }
what happen if the code throws unrelated exception to this retry policy? do we log it here? if so an exception will get logged here and elsewhere where it is truely handled. (e.g., 429). We shouldn't log unrelated exceptions to this policy and let related other policy to handle or log the exception.
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
exception);
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
Agreed - Fixed in next iteration.
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.request.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1000) - this.durationTimer.getTime(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.debug("Received retrywith exception after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); }
logger.debug("Received retrywith exception after backoff/retry. Will fail the request.",
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { return this.retryWithRetryPolicy.shouldRetry(exception) .flatMap((retryWithResult) -> { if (retryWithResult.shouldRetry) { return Mono.just(retryWithResult); } return this.goneRetryPolicy.shouldRetry(exception) .flatMap((goneRetryResult) -> { if (!goneRetryResult.shouldRetry) { logger.debug("Operation will NOT be retried. Exception:", exception); this.end = Instant.now(); } return Mono.just(goneRetryResult); }); }); }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final StopWatch durationTimer = new StopWatch(); public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy(request, waitTimeInSeconds, durationTimer); this.retryWithRetryPolicy = new RetryWithRetryPolicy(request, waitTimeInSeconds, this.durationTimer); startStopWatch(this.durationTimer); } @Override private void stopStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.stop(); } } private void startStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.start(); } } static class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } static class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; private final StopWatch durationTimer; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public RetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; this.durationTimer = durationTimer; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.request.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1000) - this.durationTimer.getTime(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.debug("Received retrywith exception after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics{ private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final Instant start; private volatile Instant end; private volatile RetryWithException lastRetryWithException; public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy( request, waitTimeInSeconds); this.retryWithRetryPolicy = new RetryWithRetryPolicy( waitTimeInSeconds); this.start = Instant.now(); } @Override private Duration getElapsedTime() { Instant endSnapshot = this.end != null ? this.end : Instant.now(); return Duration.between(this.start, endSnapshot); } class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; public RetryWithRetryPolicy(Integer waitTimeInSeconds) { this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; GoneAndRetryWithRetryPolicy.this.lastRetryWithException = lastRetryWithException; long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
Same behavior as before - should we really change it - what is the harm?
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
exception);
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
this logs stacktrace with warning level. we are logging stacktrace with warning level inside the inner policies too. this way we will get stacktrace dumped twice. we should log stacktrace with warn only at one place. I wonder if we can remove this one and fully rely on the warn from the inner retryPolicy log?
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { return this.retryWithRetryPolicy.shouldRetry(exception) .flatMap((retryWithResult) -> { if (retryWithResult.shouldRetry) { return Mono.just(retryWithResult); } return this.goneRetryPolicy.shouldRetry(exception) .flatMap((goneRetryResult) -> { if (!goneRetryResult.shouldRetry) { logger.warn("Operation will NOT be retried. Exception:", exception); stopStopWatch(this.durationTimer); } return Mono.just(goneRetryResult); }); }); }
exception);
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { return this.retryWithRetryPolicy.shouldRetry(exception) .flatMap((retryWithResult) -> { if (retryWithResult.shouldRetry) { return Mono.just(retryWithResult); } return this.goneRetryPolicy.shouldRetry(exception) .flatMap((goneRetryResult) -> { if (!goneRetryResult.shouldRetry) { logger.debug("Operation will NOT be retried. Exception:", exception); this.end = Instant.now(); } return Mono.just(goneRetryResult); }); }); }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final StopWatch durationTimer = new StopWatch(); public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy(request, waitTimeInSeconds, durationTimer); this.retryWithRetryPolicy = new RetryWithRetryPolicy(request, waitTimeInSeconds, this.durationTimer); startStopWatch(this.durationTimer); } @Override private void stopStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.stop(); } } private void startStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.start(); } } static class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } static class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; private final StopWatch durationTimer; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public RetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; this.durationTimer = durationTimer; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.request.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.durationTimer.getTime(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics{ private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final Instant start; private volatile Instant end; private volatile RetryWithException lastRetryWithException; public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy( request, waitTimeInSeconds); this.retryWithRetryPolicy = new RetryWithRetryPolicy( waitTimeInSeconds); this.start = Instant.now(); } @Override private Duration getElapsedTime() { Instant endSnapshot = this.end != null ? this.end : Instant.now(); return Duration.between(this.start, endSnapshot); } class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; public RetryWithRetryPolicy(Integer waitTimeInSeconds) { this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; GoneAndRetryWithRetryPolicy.this.lastRetryWithException = lastRetryWithException; long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
why do we still need to handle retryWithException here? don't we have a standalone retryPolicy for that?
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
if (lastRetryWithException != null) {
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
stopwatch durationTimer is not thread-safe. previously we had accessed it with synchronized block which that also was not ideal. My suggestion is to change durationTimer type as long and make it volatile. `private volatile long durationTimerMs` That way you can safely access it everywhere and we won't need synchronized block
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.request.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.durationTimer.getTime(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); }
long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.durationTimer.getTime();
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { return this.retryWithRetryPolicy.shouldRetry(exception) .flatMap((retryWithResult) -> { if (retryWithResult.shouldRetry) { return Mono.just(retryWithResult); } return this.goneRetryPolicy.shouldRetry(exception) .flatMap((goneRetryResult) -> { if (!goneRetryResult.shouldRetry) { logger.debug("Operation will NOT be retried. Exception:", exception); this.end = Instant.now(); } return Mono.just(goneRetryResult); }); }); }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final StopWatch durationTimer = new StopWatch(); public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy(request, waitTimeInSeconds, durationTimer); this.retryWithRetryPolicy = new RetryWithRetryPolicy(request, waitTimeInSeconds, this.durationTimer); startStopWatch(this.durationTimer); } @Override private void stopStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.stop(); } } private void startStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.start(); } } static class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } static class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; private final StopWatch durationTimer; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public RetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; this.durationTimer = durationTimer; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.request.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.durationTimer.getTime(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics{ private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final Instant start; private volatile Instant end; private volatile RetryWithException lastRetryWithException; public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy( request, waitTimeInSeconds); this.retryWithRetryPolicy = new RetryWithRetryPolicy( waitTimeInSeconds); this.start = Instant.now(); } @Override private Duration getElapsedTime() { Instant endSnapshot = this.end != null ? this.end : Instant.now(); return Duration.between(this.start, endSnapshot); } class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; public RetryWithRetryPolicy(Integer waitTimeInSeconds) { this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; GoneAndRetryWithRetryPolicy.this.lastRetryWithException = lastRetryWithException; long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
thanks for clarification. makes sense.
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
exception);
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
ACK - makes sense - will make it a debug level log here
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { return this.retryWithRetryPolicy.shouldRetry(exception) .flatMap((retryWithResult) -> { if (retryWithResult.shouldRetry) { return Mono.just(retryWithResult); } return this.goneRetryPolicy.shouldRetry(exception) .flatMap((goneRetryResult) -> { if (!goneRetryResult.shouldRetry) { logger.warn("Operation will NOT be retried. Exception:", exception); stopStopWatch(this.durationTimer); } return Mono.just(goneRetryResult); }); }); }
exception);
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { return this.retryWithRetryPolicy.shouldRetry(exception) .flatMap((retryWithResult) -> { if (retryWithResult.shouldRetry) { return Mono.just(retryWithResult); } return this.goneRetryPolicy.shouldRetry(exception) .flatMap((goneRetryResult) -> { if (!goneRetryResult.shouldRetry) { logger.debug("Operation will NOT be retried. Exception:", exception); this.end = Instant.now(); } return Mono.just(goneRetryResult); }); }); }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final StopWatch durationTimer = new StopWatch(); public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy(request, waitTimeInSeconds, durationTimer); this.retryWithRetryPolicy = new RetryWithRetryPolicy(request, waitTimeInSeconds, this.durationTimer); startStopWatch(this.durationTimer); } @Override private void stopStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.stop(); } } private void startStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.start(); } } static class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } static class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; private final StopWatch durationTimer; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public RetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; this.durationTimer = durationTimer; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.request.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.durationTimer.getTime(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics{ private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final Instant start; private volatile Instant end; private volatile RetryWithException lastRetryWithException; public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy( request, waitTimeInSeconds); this.retryWithRetryPolicy = new RetryWithRetryPolicy( waitTimeInSeconds); this.start = Instant.now(); } @Override private Duration getElapsedTime() { Instant endSnapshot = this.end != null ? this.end : Instant.now(); return Duration.between(this.start, endSnapshot); } class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; public RetryWithRetryPolicy(Integer waitTimeInSeconds) { this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; GoneAndRetryWithRetryPolicy.this.lastRetryWithException = lastRetryWithException; long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
Problem is that the lastRetryWithException is state needed by both RetryWithRetryPolicy and GoneRetryPolicy - but you are right pushing it to RxDocumentServiceRequest was convenient but a hack. Changed it in latest iteration.
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
if (lastRetryWithException != null) {
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } }
Fixed in next iteration
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.request.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.durationTimer.getTime(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); }
long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.durationTimer.getTime();
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { return this.retryWithRetryPolicy.shouldRetry(exception) .flatMap((retryWithResult) -> { if (retryWithResult.shouldRetry) { return Mono.just(retryWithResult); } return this.goneRetryPolicy.shouldRetry(exception) .flatMap((goneRetryResult) -> { if (!goneRetryResult.shouldRetry) { logger.debug("Operation will NOT be retried. Exception:", exception); this.end = Instant.now(); } return Mono.just(goneRetryResult); }); }); }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final StopWatch durationTimer = new StopWatch(); public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy(request, waitTimeInSeconds, durationTimer); this.retryWithRetryPolicy = new RetryWithRetryPolicy(request, waitTimeInSeconds, this.durationTimer); startStopWatch(this.durationTimer); } @Override private void stopStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.stop(); } } private void startStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.start(); } } static class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final StopWatch durationTimer; private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { checkNotNull(request, "request must not be null."); this.request = request; this.durationTimer = durationTimer; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } static class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; private final StopWatch durationTimer; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public RetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds, StopWatch durationTimer) { this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; this.durationTimer = durationTimer; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.request.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.durationTimer.getTime(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics{ private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final Instant start; private volatile Instant end; private volatile RetryWithException lastRetryWithException; public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy( request, waitTimeInSeconds); this.retryWithRetryPolicy = new RetryWithRetryPolicy( waitTimeInSeconds); this.start = Instant.now(); } @Override private Duration getElapsedTime() { Instant endSnapshot = this.end != null ? this.end : Instant.now(); return Duration.between(this.start, endSnapshot); } class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; public RetryWithRetryPolicy(Integer waitTimeInSeconds) { this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; GoneAndRetryWithRetryPolicy.this.lastRetryWithException = lastRetryWithException; long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
Good catch :-)
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.getElapsedTimeSupplier.get().toSeconds(); int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); }
long remainingSeconds = this.waitTimeInSeconds - this.getElapsedTimeSupplier.get().toSeconds();
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { return this.retryWithRetryPolicy.shouldRetry(exception) .flatMap((retryWithResult) -> { if (retryWithResult.shouldRetry) { return Mono.just(retryWithResult); } return this.goneRetryPolicy.shouldRetry(exception) .flatMap((goneRetryResult) -> { if (!goneRetryResult.shouldRetry) { logger.debug("Operation will NOT be retried. Exception:", exception); this.end = Instant.now(); } return Mono.just(goneRetryResult); }); }); }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics implements LastRetryWithExceptionHolder, LastRetryWithExceptionProvider { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final Instant start; private volatile Instant end; private RetryWithException lastRetryWithException; public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy( request, waitTimeInSeconds, this::getElapsedTime, this); this.retryWithRetryPolicy = new RetryWithRetryPolicy( waitTimeInSeconds, this::getElapsedTime, this); this.start = Instant.now(); } @Override public void setLastRetryWithException(RetryWithException lastRetryWithException) { this.lastRetryWithException = lastRetryWithException; } @Override public RetryWithException getLastRetryWithException() { return this.lastRetryWithException; } @Override private Duration getElapsedTime() { Instant endSnapshot = this.end != null ? this.end : Instant.now(); return Duration.between(this.start, endSnapshot); } static class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final Supplier<Duration> getElapsedTimeSupplier; private final int waitTimeInSeconds; private final LastRetryWithExceptionProvider lastRetryWithExceptionProvider; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, Supplier<Duration> getElapsedTimeSupplier, LastRetryWithExceptionProvider lastRetryWithExceptionProvider) { checkNotNull(request, "request must not be null."); this.request = request; this.getElapsedTimeSupplier = getElapsedTimeSupplier; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; this.lastRetryWithExceptionProvider = lastRetryWithExceptionProvider; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = lastRetryWithExceptionProvider.getLastRetryWithException(); if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.getElapsedTimeSupplier.get().toSeconds(); int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } static class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; private final Supplier<Duration> getElapsedTimeSupplier; private final LastRetryWithExceptionHolder lastRetryWithExceptionHolder; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public RetryWithRetryPolicy(Integer waitTimeInSeconds, Supplier<Duration> getElapsedTimeSupplier, LastRetryWithExceptionHolder lastRetryWithExceptionHolder) { this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; this.getElapsedTimeSupplier = getElapsedTimeSupplier; this.lastRetryWithExceptionHolder = lastRetryWithExceptionHolder; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.lastRetryWithExceptionHolder.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.getElapsedTimeSupplier.get().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics{ private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final Instant start; private volatile Instant end; private volatile RetryWithException lastRetryWithException; public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy( request, waitTimeInSeconds); this.retryWithRetryPolicy = new RetryWithRetryPolicy( waitTimeInSeconds); this.start = Instant.now(); } @Override private Duration getElapsedTime() { Instant endSnapshot = this.end != null ? this.end : Instant.now(); return Duration.between(this.start, endSnapshot); } class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; public RetryWithRetryPolicy(Integer waitTimeInSeconds) { this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; GoneAndRetryWithRetryPolicy.this.lastRetryWithException = lastRetryWithException; long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
Fixed
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.getElapsedTimeSupplier.get().toSeconds(); int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); }
long remainingSeconds = this.waitTimeInSeconds - this.getElapsedTimeSupplier.get().toSeconds();
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { return this.retryWithRetryPolicy.shouldRetry(exception) .flatMap((retryWithResult) -> { if (retryWithResult.shouldRetry) { return Mono.just(retryWithResult); } return this.goneRetryPolicy.shouldRetry(exception) .flatMap((goneRetryResult) -> { if (!goneRetryResult.shouldRetry) { logger.debug("Operation will NOT be retried. Exception:", exception); this.end = Instant.now(); } return Mono.just(goneRetryResult); }); }); }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics implements LastRetryWithExceptionHolder, LastRetryWithExceptionProvider { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final Instant start; private volatile Instant end; private RetryWithException lastRetryWithException; public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy( request, waitTimeInSeconds, this::getElapsedTime, this); this.retryWithRetryPolicy = new RetryWithRetryPolicy( waitTimeInSeconds, this::getElapsedTime, this); this.start = Instant.now(); } @Override public void setLastRetryWithException(RetryWithException lastRetryWithException) { this.lastRetryWithException = lastRetryWithException; } @Override public RetryWithException getLastRetryWithException() { return this.lastRetryWithException; } @Override private Duration getElapsedTime() { Instant endSnapshot = this.end != null ? this.end : Instant.now(); return Duration.between(this.start, endSnapshot); } static class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final Supplier<Duration> getElapsedTimeSupplier; private final int waitTimeInSeconds; private final LastRetryWithExceptionProvider lastRetryWithExceptionProvider; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds, Supplier<Duration> getElapsedTimeSupplier, LastRetryWithExceptionProvider lastRetryWithExceptionProvider) { checkNotNull(request, "request must not be null."); this.request = request; this.getElapsedTimeSupplier = getElapsedTimeSupplier; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; this.lastRetryWithExceptionProvider = lastRetryWithExceptionProvider; } private boolean isRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return true; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null; } return false; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = lastRetryWithExceptionProvider.getLastRetryWithException(); if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (!isRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - this.getElapsedTimeSupplier.get().toSeconds(); int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } static class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; private final Supplier<Duration> getElapsedTimeSupplier; private final LastRetryWithExceptionHolder lastRetryWithExceptionHolder; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public RetryWithRetryPolicy(Integer waitTimeInSeconds, Supplier<Duration> getElapsedTimeSupplier, LastRetryWithExceptionHolder lastRetryWithExceptionHolder) { this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; this.getElapsedTimeSupplier = getElapsedTimeSupplier; this.lastRetryWithExceptionHolder = lastRetryWithExceptionHolder; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.lastRetryWithExceptionHolder.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - this.getElapsedTimeSupplier.get().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics{ private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final GoneRetryPolicy goneRetryPolicy; private final RetryWithRetryPolicy retryWithRetryPolicy; private final Instant start; private volatile Instant end; private volatile RetryWithException lastRetryWithException; public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.goneRetryPolicy = new GoneRetryPolicy( request, waitTimeInSeconds); this.retryWithRetryPolicy = new RetryWithRetryPolicy( waitTimeInSeconds); this.start = Instant.now(); } @Override private Duration getElapsedTime() { Instant endSnapshot = this.end != null ? this.end : Instant.now(); return Duration.between(this.start, endSnapshot); } class GoneRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneRetryPolicy.INITIAL_BACKOFF_TIME; private final int waitTimeInSeconds; public GoneRetryPolicy( RxDocumentServiceRequest request, Integer waitTimeInSeconds) { checkNotNull(request, "request must not be null."); this.request = request; this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } private boolean isNonRetryableException(Exception exception) { if (exception instanceof GoneException || exception instanceof RetryWithException || exception instanceof PartitionIsMigratingException || exception instanceof PartitionKeyRangeIsSplittingException) { return false; } if (exception instanceof InvalidPartitionException) { return this.request.getPartitionKeyRangeIdentity() != null && this.request.getPartitionKeyRangeIdentity().getCollectionRid() != null; } return true; } private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received {} after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received {} after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow; Duration backoffTime = Duration.ofSeconds(0); Duration timeout; boolean forceRefreshAddressCache; if (isNonRetryableException(exception)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } long remainingSeconds = this.waitTimeInSeconds - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis() / 1_000L; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { exceptionToThrow = logAndWrapExceptionWithLastRetryWithException(exception); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); Pair<Mono<ShouldRetryResult>, Boolean> exceptionHandlingResult = handleException(exception); Mono<ShouldRetryResult> result = exceptionHandlingResult.getLeft(); if (result != null) { return result; } forceRefreshAddressCache = exceptionHandlingResult.getRight(); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } private Pair<Mono<ShouldRetryResult>, Boolean> handleException(Exception exception) { if (exception instanceof GoneException) { return handleGoneException((GoneException)exception); } else if (exception instanceof PartitionIsMigratingException) { return handlePartitionIsMigratingException((PartitionIsMigratingException)exception); } else if (exception instanceof InvalidPartitionException) { return handleInvalidPartitionException((InvalidPartitionException)exception); } else if (exception instanceof PartitionKeyRangeIsSplittingException) { return handlePartitionKeyIsSplittingException((PartitionKeyRangeIsSplittingException) exception); } throw new IllegalStateException("Invalid exception type", exception); } private Pair<Mono<ShouldRetryResult>, Boolean> handleGoneException(GoneException exception) { logger.info("Received gone exception, will retry, {}", exception.toString()); return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionIsMigratingException(PartitionIsMigratingException exception) { logger.info("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; return Pair.of(null, true); } private Pair<Mono<ShouldRetryResult>, Boolean> handlePartitionKeyIsSplittingException(PartitionKeyRangeIsSplittingException exception) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; return Pair.of(null, false); } private Pair<Mono<ShouldRetryResult>, Boolean> handleInvalidPartitionException(InvalidPartitionException exception) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Pair.of( Mono.just(ShouldRetryResult.error(BridgeInternal.createServiceUnavailableException(exception))), false); } logger.info("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; return Pair.of(null, false); } } class RetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_MS = 15000; private final static int INITIAL_BACKOFF_TIME_MS = 10; private final static int BACK_OFF_MULTIPLIER = 2; private volatile int attemptCount = 1; private volatile int currentBackoffMilliseconds = RetryWithRetryPolicy.INITIAL_BACKOFF_TIME_MS; private final int waitTimeInSeconds; public RetryWithRetryPolicy(Integer waitTimeInSeconds) { this.waitTimeInSeconds = waitTimeInSeconds != null ? waitTimeInSeconds : DEFAULT_WAIT_TIME_IN_SECONDS; } @Override public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; GoneAndRetryWithRetryPolicy.this.lastRetryWithException = lastRetryWithException; long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); } } }
So, effectively we aren't allowing Windows style newlines in logging?
private static String sanitizeLogMessageInput(String logMessage) { return CRLF_PATTERN.matcher(logMessage).replaceAll(""); }
return CRLF_PATTERN.matcher(logMessage).replaceAll("");
private static String sanitizeLogMessageInput(String logMessage) { return CRLF_PATTERN.matcher(logMessage).replaceAll(""); }
class name using the {@link LoggerFactory}
class name using the {@link LoggerFactory}
it can be \r, \n or \r\n. The regex will cover all scenarios.
private static String sanitizeLogMessageInput(String logMessage) { return CRLF_PATTERN.matcher(logMessage).replaceAll(""); }
return CRLF_PATTERN.matcher(logMessage).replaceAll("");
private static String sanitizeLogMessageInput(String logMessage) { return CRLF_PATTERN.matcher(logMessage).replaceAll(""); }
class name using the {@link LoggerFactory}
class name using the {@link LoggerFactory}
Is it possible that one of the passed scopes contains substring like ".default", e.g. "my.default"?
private ClientRegistration azureClientRegistration() { String tenantId = aadAuthenticationProperties.getTenantId().trim(); Assert.hasText(tenantId, "azure.activedirectory.tenant-id should have text."); Assert.doesNotContain(tenantId, " ", "azure.activedirectory.tenant-id should not contain ' '."); Assert.doesNotContain(tenantId, "/", "azure.activedirectory.tenant-id should not contain '/'."); List<String> scope = aadAuthenticationProperties.getScope(); if (!scope.toString().contains(".default")) { if (aadAuthenticationProperties.allowedGroupsConfigured() && !scope.contains("https: ) { scope.add("https: LOGGER.warn("scope 'https: } if (!scope.contains("openid")) { scope.add("openid"); LOGGER.warn("scope 'openid' has been added."); } if (!scope.contains("profile")) { scope.add("profile"); LOGGER.warn("scope 'profile' has been added."); } } return ClientRegistration.withRegistrationId("azure") .clientId(aadAuthenticationProperties.getClientId()) .clientSecret(aadAuthenticationProperties.getClientSecret()) .clientAuthenticationMethod(ClientAuthenticationMethod.POST) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope(scope) .authorizationUri( String.format( "https: tenantId ) ) .tokenUri( String.format( "https: tenantId ) ) .userInfoUri("https: .userNameAttributeName(AADTokenClaim.NAME) .jwkSetUri( String.format( "https: tenantId ) ) .clientName("Azure") .build(); }
if (!scope.toString().contains(".default")) {
private ClientRegistration azureClientRegistration() { String tenantId = aadAuthenticationProperties.getTenantId().trim(); Assert.hasText(tenantId, "azure.activedirectory.tenant-id should have text."); Assert.doesNotContain(tenantId, " ", "azure.activedirectory.tenant-id should not contain ' '."); Assert.doesNotContain(tenantId, "/", "azure.activedirectory.tenant-id should not contain '/'."); List<String> scope = aadAuthenticationProperties.getScope(); if (!scope.toString().contains(".default")) { if (aadAuthenticationProperties.allowedGroupsConfigured() && !scope.contains("https: ) { scope.add("https: LOGGER.warn("scope 'https: } if (!scope.contains("openid")) { scope.add("openid"); LOGGER.warn("scope 'openid' has been added."); } if (!scope.contains("profile")) { scope.add("profile"); LOGGER.warn("scope 'profile' has been added."); } } return ClientRegistration.withRegistrationId("azure") .clientId(aadAuthenticationProperties.getClientId()) .clientSecret(aadAuthenticationProperties.getClientSecret()) .clientAuthenticationMethod(ClientAuthenticationMethod.POST) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope(scope) .authorizationUri( String.format( "https: tenantId ) ) .tokenUri( String.format( "https: tenantId ) ) .userInfoUri("https: .userNameAttributeName(AADTokenClaim.NAME) .jwkSetUri( String.format( "https: tenantId ) ) .clientName("Azure") .build(); }
class AADOAuth2AutoConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2AutoConfiguration.class); private final AADAuthenticationProperties aadAuthenticationProperties; private final ServiceEndpointsProperties serviceEndpointsProperties; public AADOAuth2AutoConfiguration(AADAuthenticationProperties aadAuthProperties, ServiceEndpointsProperties serviceEndpointsProperties) { this.aadAuthenticationProperties = aadAuthProperties; this.serviceEndpointsProperties = serviceEndpointsProperties; } @Bean @ConditionalOnProperty(prefix = "azure.activedirectory.user-group", value = "allowed-groups") public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { return new AADOAuth2UserService(aadAuthenticationProperties, serviceEndpointsProperties); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(azureClientRegistration()); } @PostConstruct private void sendTelemetry() { if (aadAuthenticationProperties.isAllowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(AADOAuth2AutoConfiguration.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
class AADOAuth2AutoConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2AutoConfiguration.class); private final AADAuthenticationProperties aadAuthenticationProperties; private final ServiceEndpointsProperties serviceEndpointsProperties; public AADOAuth2AutoConfiguration(AADAuthenticationProperties aadAuthProperties, ServiceEndpointsProperties serviceEndpointsProperties) { this.aadAuthenticationProperties = aadAuthProperties; this.serviceEndpointsProperties = serviceEndpointsProperties; } @Bean @ConditionalOnProperty(prefix = "azure.activedirectory.user-group", value = "allowed-groups") public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { return new AADOAuth2UserService(aadAuthenticationProperties, serviceEndpointsProperties); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(azureClientRegistration()); } @PostConstruct private void sendTelemetry() { if (aadAuthenticationProperties.isAllowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(AADOAuth2AutoConfiguration.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
I manually searched all permissions provided in Azure portal, and haven't found there are any scopes contained ".default" in their scope names.
private ClientRegistration azureClientRegistration() { String tenantId = aadAuthenticationProperties.getTenantId().trim(); Assert.hasText(tenantId, "azure.activedirectory.tenant-id should have text."); Assert.doesNotContain(tenantId, " ", "azure.activedirectory.tenant-id should not contain ' '."); Assert.doesNotContain(tenantId, "/", "azure.activedirectory.tenant-id should not contain '/'."); List<String> scope = aadAuthenticationProperties.getScope(); if (!scope.toString().contains(".default")) { if (aadAuthenticationProperties.allowedGroupsConfigured() && !scope.contains("https: ) { scope.add("https: LOGGER.warn("scope 'https: } if (!scope.contains("openid")) { scope.add("openid"); LOGGER.warn("scope 'openid' has been added."); } if (!scope.contains("profile")) { scope.add("profile"); LOGGER.warn("scope 'profile' has been added."); } } return ClientRegistration.withRegistrationId("azure") .clientId(aadAuthenticationProperties.getClientId()) .clientSecret(aadAuthenticationProperties.getClientSecret()) .clientAuthenticationMethod(ClientAuthenticationMethod.POST) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope(scope) .authorizationUri( String.format( "https: tenantId ) ) .tokenUri( String.format( "https: tenantId ) ) .userInfoUri("https: .userNameAttributeName(AADTokenClaim.NAME) .jwkSetUri( String.format( "https: tenantId ) ) .clientName("Azure") .build(); }
if (!scope.toString().contains(".default")) {
private ClientRegistration azureClientRegistration() { String tenantId = aadAuthenticationProperties.getTenantId().trim(); Assert.hasText(tenantId, "azure.activedirectory.tenant-id should have text."); Assert.doesNotContain(tenantId, " ", "azure.activedirectory.tenant-id should not contain ' '."); Assert.doesNotContain(tenantId, "/", "azure.activedirectory.tenant-id should not contain '/'."); List<String> scope = aadAuthenticationProperties.getScope(); if (!scope.toString().contains(".default")) { if (aadAuthenticationProperties.allowedGroupsConfigured() && !scope.contains("https: ) { scope.add("https: LOGGER.warn("scope 'https: } if (!scope.contains("openid")) { scope.add("openid"); LOGGER.warn("scope 'openid' has been added."); } if (!scope.contains("profile")) { scope.add("profile"); LOGGER.warn("scope 'profile' has been added."); } } return ClientRegistration.withRegistrationId("azure") .clientId(aadAuthenticationProperties.getClientId()) .clientSecret(aadAuthenticationProperties.getClientSecret()) .clientAuthenticationMethod(ClientAuthenticationMethod.POST) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope(scope) .authorizationUri( String.format( "https: tenantId ) ) .tokenUri( String.format( "https: tenantId ) ) .userInfoUri("https: .userNameAttributeName(AADTokenClaim.NAME) .jwkSetUri( String.format( "https: tenantId ) ) .clientName("Azure") .build(); }
class AADOAuth2AutoConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2AutoConfiguration.class); private final AADAuthenticationProperties aadAuthenticationProperties; private final ServiceEndpointsProperties serviceEndpointsProperties; public AADOAuth2AutoConfiguration(AADAuthenticationProperties aadAuthProperties, ServiceEndpointsProperties serviceEndpointsProperties) { this.aadAuthenticationProperties = aadAuthProperties; this.serviceEndpointsProperties = serviceEndpointsProperties; } @Bean @ConditionalOnProperty(prefix = "azure.activedirectory.user-group", value = "allowed-groups") public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { return new AADOAuth2UserService(aadAuthenticationProperties, serviceEndpointsProperties); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(azureClientRegistration()); } @PostConstruct private void sendTelemetry() { if (aadAuthenticationProperties.isAllowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(AADOAuth2AutoConfiguration.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
class AADOAuth2AutoConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2AutoConfiguration.class); private final AADAuthenticationProperties aadAuthenticationProperties; private final ServiceEndpointsProperties serviceEndpointsProperties; public AADOAuth2AutoConfiguration(AADAuthenticationProperties aadAuthProperties, ServiceEndpointsProperties serviceEndpointsProperties) { this.aadAuthenticationProperties = aadAuthProperties; this.serviceEndpointsProperties = serviceEndpointsProperties; } @Bean @ConditionalOnProperty(prefix = "azure.activedirectory.user-group", value = "allowed-groups") public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { return new AADOAuth2UserService(aadAuthenticationProperties, serviceEndpointsProperties); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(azureClientRegistration()); } @PostConstruct private void sendTelemetry() { if (aadAuthenticationProperties.isAllowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(AADOAuth2AutoConfiguration.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
Why not use `Throwable`?
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Windows Credential API.", e)); } } else if (Platform.isMac()) { try { KeyChainAccessor keyChainAccessor = new KeyChainAccessor(null, serviceName, accountName); byte[] readCreds = keyChainAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Mac Native Key Chain.", e)); } } else if (Platform.isLinux()) { try { LinuxKeyRingAccessor keyRingAccessor = new LinuxKeyRingAccessor( "org.freedesktop.Secret.Generic", "service", serviceName, "account", accountName); byte[] readCreds = keyRingAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception | UnsatisfiedLinkError e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Linux Key Ring.", e)); } } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } if (CoreUtils.isNullOrEmpty(credential) || !isRefreshTokenString(credential)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please authenticate via Azure Tools plugin in VS Code IDE.")); } return credential; }
} catch (Exception | UnsatisfiedLinkError e) {
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Windows Credential API.", e)); } } else if (Platform.isMac()) { try { KeyChainAccessor keyChainAccessor = new KeyChainAccessor(null, serviceName, accountName); byte[] readCreds = keyChainAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Mac Native Key Chain.", e)); } } else if (Platform.isLinux()) { try { LinuxKeyRingAccessor keyRingAccessor = new LinuxKeyRingAccessor( "org.freedesktop.Secret.Generic", "service", serviceName, "account", accountName); byte[] readCreds = keyRingAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception | UnsatisfiedLinkError e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Linux Key Ring.", e)); } } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } if (CoreUtils.isNullOrEmpty(credential) || !isRefreshTokenString(credential)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please authenticate via Azure Tools plugin in VS Code IDE.")); } return credential; }
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); private static final Pattern REFRESH_TOKEN_PATTERN = Pattern.compile("^[-_.a-zA-Z0-9]+$"); private JsonNode getUserSettings() { JsonNode output = null; String homeDir = System.getProperty("user.home"); String settingsPath = ""; ObjectMapper mapper = new ObjectMapper(); try { if (Platform.isWindows()) { settingsPath = Paths.get(System.getenv("APPDATA"), "Code", "User", "settings.json") .toString(); } else if (Platform.isMac()) { settingsPath = Paths.get(homeDir, "Library", "Application Support", "Code", "User", "settings.json").toString(); } else if (Platform.isLinux()) { settingsPath = Paths.get(homeDir, ".config", "Code", "User", "settings.json") .toString(); } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } File settingsFile = new File(settingsPath); output = mapper.readTree(settingsFile); } catch (Exception e) { return null; } return output; } /** * Get the user configured settings of Visual Studio code. * * @return a Map containing Vs Code user settings */ public Map<String, String> getUserSettingsDetails() { JsonNode userSettings = getUserSettings(); Map<String, String> details = new HashMap<>(); String tenant = null; String cloud = "AzureCloud"; if (userSettings != null && !userSettings.isNull()) { if (userSettings.has("azure.tenant")) { tenant = userSettings.get("azure.tenant").asText(); } if (userSettings.has("azure.cloud")) { cloud = userSettings.get("azure.cloud").asText(); } } if (!CoreUtils.isNullOrEmpty(tenant)) { details.put("tenant", tenant); } details.put("cloud", cloud); return details; } /** * Get the credential for the specified service and account name. * * @param serviceName the name of the service to lookup. * @param accountName the account of the service to lookup. * @return the credential. */ private boolean isRefreshTokenString(String str) { return REFRESH_TOKEN_PATTERN.matcher(str).matches(); } /** * Get the auth host of the specified {@code azureEnvironment}. * * @return the auth host. */ public String getAzureAuthHost(String cloud) { switch (cloud) { case "AzureCloud": return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; case "AzureChina": return AzureAuthorityHosts.AZURE_CHINA; case "AzureGermanCloud": return AzureAuthorityHosts.AZURE_GERMANY; case "AzureUSGovernment": return AzureAuthorityHosts.AZURE_GOVERNMENT; default: return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; } } }
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); private static final Pattern REFRESH_TOKEN_PATTERN = Pattern.compile("^[-_.a-zA-Z0-9]+$"); private JsonNode getUserSettings() { JsonNode output = null; String homeDir = System.getProperty("user.home"); String settingsPath = ""; ObjectMapper mapper = new ObjectMapper(); try { if (Platform.isWindows()) { settingsPath = Paths.get(System.getenv("APPDATA"), "Code", "User", "settings.json") .toString(); } else if (Platform.isMac()) { settingsPath = Paths.get(homeDir, "Library", "Application Support", "Code", "User", "settings.json").toString(); } else if (Platform.isLinux()) { settingsPath = Paths.get(homeDir, ".config", "Code", "User", "settings.json") .toString(); } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } File settingsFile = new File(settingsPath); output = mapper.readTree(settingsFile); } catch (Exception e) { return null; } return output; } /** * Get the user configured settings of Visual Studio code. * * @return a Map containing Vs Code user settings */ public Map<String, String> getUserSettingsDetails() { JsonNode userSettings = getUserSettings(); Map<String, String> details = new HashMap<>(); String tenant = null; String cloud = "AzureCloud"; if (userSettings != null && !userSettings.isNull()) { if (userSettings.has("azure.tenant")) { tenant = userSettings.get("azure.tenant").asText(); } if (userSettings.has("azure.cloud")) { cloud = userSettings.get("azure.cloud").asText(); } } if (!CoreUtils.isNullOrEmpty(tenant)) { details.put("tenant", tenant); } details.put("cloud", cloud); return details; } /** * Get the credential for the specified service and account name. * * @param serviceName the name of the service to lookup. * @param accountName the account of the service to lookup. * @return the credential. */ private boolean isRefreshTokenString(String str) { return REFRESH_TOKEN_PATTERN.matcher(str).matches(); } /** * Get the auth host of the specified {@code azureEnvironment}. * * @return the auth host. */ public String getAzureAuthHost(String cloud) { switch (cloud) { case "AzureCloud": return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; case "AzureChina": return AzureAuthorityHosts.AZURE_CHINA; case "AzureGermanCloud": return AzureAuthorityHosts.AZURE_GERMANY; case "AzureUSGovernment": return AzureAuthorityHosts.AZURE_GOVERNMENT; default: return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; } } }
Throwable will work too, but didn't want to aggressively block other Error types which may qualify to fail the credential.
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Windows Credential API.", e)); } } else if (Platform.isMac()) { try { KeyChainAccessor keyChainAccessor = new KeyChainAccessor(null, serviceName, accountName); byte[] readCreds = keyChainAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Mac Native Key Chain.", e)); } } else if (Platform.isLinux()) { try { LinuxKeyRingAccessor keyRingAccessor = new LinuxKeyRingAccessor( "org.freedesktop.Secret.Generic", "service", serviceName, "account", accountName); byte[] readCreds = keyRingAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception | UnsatisfiedLinkError e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Linux Key Ring.", e)); } } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } if (CoreUtils.isNullOrEmpty(credential) || !isRefreshTokenString(credential)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please authenticate via Azure Tools plugin in VS Code IDE.")); } return credential; }
} catch (Exception | UnsatisfiedLinkError e) {
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Windows Credential API.", e)); } } else if (Platform.isMac()) { try { KeyChainAccessor keyChainAccessor = new KeyChainAccessor(null, serviceName, accountName); byte[] readCreds = keyChainAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Mac Native Key Chain.", e)); } } else if (Platform.isLinux()) { try { LinuxKeyRingAccessor keyRingAccessor = new LinuxKeyRingAccessor( "org.freedesktop.Secret.Generic", "service", serviceName, "account", accountName); byte[] readCreds = keyRingAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception | UnsatisfiedLinkError e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Linux Key Ring.", e)); } } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } if (CoreUtils.isNullOrEmpty(credential) || !isRefreshTokenString(credential)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please authenticate via Azure Tools plugin in VS Code IDE.")); } return credential; }
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); private static final Pattern REFRESH_TOKEN_PATTERN = Pattern.compile("^[-_.a-zA-Z0-9]+$"); private JsonNode getUserSettings() { JsonNode output = null; String homeDir = System.getProperty("user.home"); String settingsPath = ""; ObjectMapper mapper = new ObjectMapper(); try { if (Platform.isWindows()) { settingsPath = Paths.get(System.getenv("APPDATA"), "Code", "User", "settings.json") .toString(); } else if (Platform.isMac()) { settingsPath = Paths.get(homeDir, "Library", "Application Support", "Code", "User", "settings.json").toString(); } else if (Platform.isLinux()) { settingsPath = Paths.get(homeDir, ".config", "Code", "User", "settings.json") .toString(); } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } File settingsFile = new File(settingsPath); output = mapper.readTree(settingsFile); } catch (Exception e) { return null; } return output; } /** * Get the user configured settings of Visual Studio code. * * @return a Map containing Vs Code user settings */ public Map<String, String> getUserSettingsDetails() { JsonNode userSettings = getUserSettings(); Map<String, String> details = new HashMap<>(); String tenant = null; String cloud = "AzureCloud"; if (userSettings != null && !userSettings.isNull()) { if (userSettings.has("azure.tenant")) { tenant = userSettings.get("azure.tenant").asText(); } if (userSettings.has("azure.cloud")) { cloud = userSettings.get("azure.cloud").asText(); } } if (!CoreUtils.isNullOrEmpty(tenant)) { details.put("tenant", tenant); } details.put("cloud", cloud); return details; } /** * Get the credential for the specified service and account name. * * @param serviceName the name of the service to lookup. * @param accountName the account of the service to lookup. * @return the credential. */ private boolean isRefreshTokenString(String str) { return REFRESH_TOKEN_PATTERN.matcher(str).matches(); } /** * Get the auth host of the specified {@code azureEnvironment}. * * @return the auth host. */ public String getAzureAuthHost(String cloud) { switch (cloud) { case "AzureCloud": return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; case "AzureChina": return AzureAuthorityHosts.AZURE_CHINA; case "AzureGermanCloud": return AzureAuthorityHosts.AZURE_GERMANY; case "AzureUSGovernment": return AzureAuthorityHosts.AZURE_GOVERNMENT; default: return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; } } }
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); private static final Pattern REFRESH_TOKEN_PATTERN = Pattern.compile("^[-_.a-zA-Z0-9]+$"); private JsonNode getUserSettings() { JsonNode output = null; String homeDir = System.getProperty("user.home"); String settingsPath = ""; ObjectMapper mapper = new ObjectMapper(); try { if (Platform.isWindows()) { settingsPath = Paths.get(System.getenv("APPDATA"), "Code", "User", "settings.json") .toString(); } else if (Platform.isMac()) { settingsPath = Paths.get(homeDir, "Library", "Application Support", "Code", "User", "settings.json").toString(); } else if (Platform.isLinux()) { settingsPath = Paths.get(homeDir, ".config", "Code", "User", "settings.json") .toString(); } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } File settingsFile = new File(settingsPath); output = mapper.readTree(settingsFile); } catch (Exception e) { return null; } return output; } /** * Get the user configured settings of Visual Studio code. * * @return a Map containing Vs Code user settings */ public Map<String, String> getUserSettingsDetails() { JsonNode userSettings = getUserSettings(); Map<String, String> details = new HashMap<>(); String tenant = null; String cloud = "AzureCloud"; if (userSettings != null && !userSettings.isNull()) { if (userSettings.has("azure.tenant")) { tenant = userSettings.get("azure.tenant").asText(); } if (userSettings.has("azure.cloud")) { cloud = userSettings.get("azure.cloud").asText(); } } if (!CoreUtils.isNullOrEmpty(tenant)) { details.put("tenant", tenant); } details.put("cloud", cloud); return details; } /** * Get the credential for the specified service and account name. * * @param serviceName the name of the service to lookup. * @param accountName the account of the service to lookup. * @return the credential. */ private boolean isRefreshTokenString(String str) { return REFRESH_TOKEN_PATTERN.matcher(str).matches(); } /** * Get the auth host of the specified {@code azureEnvironment}. * * @return the auth host. */ public String getAzureAuthHost(String cloud) { switch (cloud) { case "AzureCloud": return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; case "AzureChina": return AzureAuthorityHosts.AZURE_CHINA; case "AzureGermanCloud": return AzureAuthorityHosts.AZURE_GERMANY; case "AzureUSGovernment": return AzureAuthorityHosts.AZURE_GOVERNMENT; default: return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; } } }
For internal consistency you should consider changing the name on the identityClientOptions too
public ClientCertificateCredentialBuilder sendCertificateChain(boolean sendCertificateChain) { this.identityClientOptions.setIncludeX5c(sendCertificateChain); return this; }
this.identityClientOptions.setIncludeX5c(sendCertificateChain);
public ClientCertificateCredentialBuilder sendCertificateChain(boolean sendCertificateChain) { this.identityClientOptions.setIncludeX5c(sendCertificateChain); return this; }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; private final ClientLogger logger = new ClientLogger(ClientCertificateCredentialBuilder.class); /** * Sets the path of the PEM certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { this.clientCertificatePath = certificatePath; return this; } /** * Sets the input stream holding the PEM certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the path and password of the PFX certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the input stream holding the PFX certificate and its password for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request * and enable subject name / issuer based authentication. The default value is false. * * @param sendCertificateChain the flag to indicate if certificate chain should be sent as part of authentication * request. * @return An updated instance of this builder. */ /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); if (clientCertificate != null && clientCertificatePath != null) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Both certificate input stream and " + "certificate path are provided in ClientCertificateCredentialBuilder. Only one of them should " + "be provided.")); } return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); } }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; private final ClientLogger logger = new ClientLogger(ClientCertificateCredentialBuilder.class); /** * Sets the path of the PEM certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { this.clientCertificatePath = certificatePath; return this; } /** * Sets the input stream holding the PEM certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the path and password of the PFX certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the input stream holding the PFX certificate and its password for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request * and enable subject name / issuer based authentication. The default value is false. * * @param sendCertificateChain the flag to indicate if certificate chain should be sent as part of authentication * request. * @return An updated instance of this builder. */ /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); if (clientCertificate != null && clientCertificatePath != null) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Both certificate input stream and " + "certificate path are provided in ClientCertificateCredentialBuilder. Only one of them should " + "be provided.")); } return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); } }
I would expect all strings going into logs would refer to it as "VS Code"?
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Windows Credential API.", e)); } } else if (Platform.isMac()) { try { KeyChainAccessor keyChainAccessor = new KeyChainAccessor(null, serviceName, accountName); byte[] readCreds = keyChainAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Mac Native Key Chain.", e)); } } else if (Platform.isLinux()) { try { LinuxKeyRingAccessor keyRingAccessor = new LinuxKeyRingAccessor( "org.freedesktop.Secret.Generic", "service", serviceName, "account", accountName); byte[] readCreds = keyRingAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception | UnsatisfiedLinkError e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Linux Key Ring.", e)); } } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } if (CoreUtils.isNullOrEmpty(credential) || !isRefreshTokenString(credential)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please authenticate via Azure Tools plugin in VS Code IDE.")); } return credential; }
"Failed to read Vs Code credentials from Linux Key Ring.", e));
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Windows Credential API.", e)); } } else if (Platform.isMac()) { try { KeyChainAccessor keyChainAccessor = new KeyChainAccessor(null, serviceName, accountName); byte[] readCreds = keyChainAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Mac Native Key Chain.", e)); } } else if (Platform.isLinux()) { try { LinuxKeyRingAccessor keyRingAccessor = new LinuxKeyRingAccessor( "org.freedesktop.Secret.Generic", "service", serviceName, "account", accountName); byte[] readCreds = keyRingAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (Exception | UnsatisfiedLinkError e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Linux Key Ring.", e)); } } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } if (CoreUtils.isNullOrEmpty(credential) || !isRefreshTokenString(credential)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please authenticate via Azure Tools plugin in VS Code IDE.")); } return credential; }
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); private static final Pattern REFRESH_TOKEN_PATTERN = Pattern.compile("^[-_.a-zA-Z0-9]+$"); private JsonNode getUserSettings() { JsonNode output = null; String homeDir = System.getProperty("user.home"); String settingsPath = ""; ObjectMapper mapper = new ObjectMapper(); try { if (Platform.isWindows()) { settingsPath = Paths.get(System.getenv("APPDATA"), "Code", "User", "settings.json") .toString(); } else if (Platform.isMac()) { settingsPath = Paths.get(homeDir, "Library", "Application Support", "Code", "User", "settings.json").toString(); } else if (Platform.isLinux()) { settingsPath = Paths.get(homeDir, ".config", "Code", "User", "settings.json") .toString(); } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } File settingsFile = new File(settingsPath); output = mapper.readTree(settingsFile); } catch (Exception e) { return null; } return output; } /** * Get the user configured settings of Visual Studio code. * * @return a Map containing Vs Code user settings */ public Map<String, String> getUserSettingsDetails() { JsonNode userSettings = getUserSettings(); Map<String, String> details = new HashMap<>(); String tenant = null; String cloud = "AzureCloud"; if (userSettings != null && !userSettings.isNull()) { if (userSettings.has("azure.tenant")) { tenant = userSettings.get("azure.tenant").asText(); } if (userSettings.has("azure.cloud")) { cloud = userSettings.get("azure.cloud").asText(); } } if (!CoreUtils.isNullOrEmpty(tenant)) { details.put("tenant", tenant); } details.put("cloud", cloud); return details; } /** * Get the credential for the specified service and account name. * * @param serviceName the name of the service to lookup. * @param accountName the account of the service to lookup. * @return the credential. */ private boolean isRefreshTokenString(String str) { return REFRESH_TOKEN_PATTERN.matcher(str).matches(); } /** * Get the auth host of the specified {@code azureEnvironment}. * * @return the auth host. */ public String getAzureAuthHost(String cloud) { switch (cloud) { case "AzureCloud": return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; case "AzureChina": return AzureAuthorityHosts.AZURE_CHINA; case "AzureGermanCloud": return AzureAuthorityHosts.AZURE_GERMANY; case "AzureUSGovernment": return AzureAuthorityHosts.AZURE_GOVERNMENT; default: return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; } } }
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); private static final Pattern REFRESH_TOKEN_PATTERN = Pattern.compile("^[-_.a-zA-Z0-9]+$"); private JsonNode getUserSettings() { JsonNode output = null; String homeDir = System.getProperty("user.home"); String settingsPath = ""; ObjectMapper mapper = new ObjectMapper(); try { if (Platform.isWindows()) { settingsPath = Paths.get(System.getenv("APPDATA"), "Code", "User", "settings.json") .toString(); } else if (Platform.isMac()) { settingsPath = Paths.get(homeDir, "Library", "Application Support", "Code", "User", "settings.json").toString(); } else if (Platform.isLinux()) { settingsPath = Paths.get(homeDir, ".config", "Code", "User", "settings.json") .toString(); } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } File settingsFile = new File(settingsPath); output = mapper.readTree(settingsFile); } catch (Exception e) { return null; } return output; } /** * Get the user configured settings of Visual Studio code. * * @return a Map containing Vs Code user settings */ public Map<String, String> getUserSettingsDetails() { JsonNode userSettings = getUserSettings(); Map<String, String> details = new HashMap<>(); String tenant = null; String cloud = "AzureCloud"; if (userSettings != null && !userSettings.isNull()) { if (userSettings.has("azure.tenant")) { tenant = userSettings.get("azure.tenant").asText(); } if (userSettings.has("azure.cloud")) { cloud = userSettings.get("azure.cloud").asText(); } } if (!CoreUtils.isNullOrEmpty(tenant)) { details.put("tenant", tenant); } details.put("cloud", cloud); return details; } /** * Get the credential for the specified service and account name. * * @param serviceName the name of the service to lookup. * @param accountName the account of the service to lookup. * @return the credential. */ private boolean isRefreshTokenString(String str) { return REFRESH_TOKEN_PATTERN.matcher(str).matches(); } /** * Get the auth host of the specified {@code azureEnvironment}. * * @return the auth host. */ public String getAzureAuthHost(String cloud) { switch (cloud) { case "AzureCloud": return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; case "AzureChina": return AzureAuthorityHosts.AZURE_CHINA; case "AzureGermanCloud": return AzureAuthorityHosts.AZURE_GERMANY; case "AzureUSGovernment": return AzureAuthorityHosts.AZURE_GOVERNMENT; default: return AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; } } }
nit: the tabbing needs to be fixed here
public void createRelationship() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class) .subscribe(createdRelationship -> System.out.println( "Created relationship with Id: " + createdRelationship.getId() + " from: " + createdRelationship.getSourceId() + " to: " + createdRelationship.getTargetId())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class) .subscribe(createRelationshipString -> System.out.println("Created relationship: " + createRelationshipString)); }
"myRelationshipId",
public void createRelationship() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class) .subscribe(createdRelationship -> System.out.println( "Created relationship with Id: " + createdRelationship.getId() + " from: " + createdRelationship.getSourceId() + " to: " + createdRelationship.getTargetId())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class) .subscribe(createRelationshipString -> System.out.println("Created relationship: " + createRelationshipString)); }
class DigitalTwinsAsyncClientJavaDocCodeSnippets extends CodeSnippetBase { private final DigitalTwinsAsyncClient digitalTwinsAsyncClient; DigitalTwinsAsyncClientJavaDocCodeSnippets(){ digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); } public DigitalTwinsAsyncClient createDigitalTwinsAsyncClient() { String tenantId = getTenenatId(); String clientId = getClientId(); String clientSecret = getClientSecret(); String digitalTwinsEndpointUrl = getEndpointUrl(); DigitalTwinsAsyncClient digitalTwinsAsyncClient = new DigitalTwinsClientBuilder() .credential( new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build()) .endpoint(digitalTwinsEndpointUrl) .buildAsyncClient(); return digitalTwinsAsyncClient; } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwin(basicTwin.getId(), basicTwin, BasicDigitalTwin.class) .subscribe(response -> System.out.println("Created digital twin Id: " + response.getId())); String digitalTwinStringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwin("myDigitalTwinId", digitalTwinStringPayload, String.class) .subscribe(stringResponse -> System.out.println("Created digital twin: " + stringResponse)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwinWithResponse(){ DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicDigitalTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), basicDigitalTwin, BasicDigitalTwin.class, new CreateDigitalTwinOptions()) .subscribe(resultWithResponse -> System.out.println( "Response http status: " + resultWithResponse.getStatusCode() + " created digital twin Id: " + resultWithResponse.getValue().getId())); String stringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), stringPayload, String.class, new CreateDigitalTwinOptions()) .subscribe(stringWithResponse -> System.out.println( "Response http status: " + stringWithResponse.getStatusCode() + " created digital twin: " + stringWithResponse.getValue())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ public void getDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", BasicDigitalTwin.class) .subscribe( basicDigitalTwin -> System.out.println("Retrieved digital twin with Id: " + basicDigitalTwin.getId())); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", String.class) .subscribe(stringResult -> System.out.println("Retrieved digital twin: " + stringResult)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", BasicDigitalTwin.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin with Id: " + basicDigitalTwinWithResponse.getValue().getId() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", String.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin: " + basicDigitalTwinWithResponse.getValue() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwin( "myDigitalTwinId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwinWithResponse( "myDigitalTwinId", updateOperationUtility.getUpdateOperations(), new UpdateDigitalTwinOptions()) .subscribe(updateResponse -> System.out.println("Update completed with HTTP status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwin("myDigitalTwinId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwinWithResponse( "myDigitalTwinId", new DeleteDigitalTwinOptions()) .subscribe(deleteResponse -> System.out.println("Deleted digital twin. HTTP response status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createRelationshipWithResponse() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipWithResponse -> System.out.println( "Created relationship with Id: " + createdRelationshipWithResponse.getValue().getId() + " from: " + createdRelationshipWithResponse.getValue().getSourceId() + " to: " + createdRelationshipWithResponse.getValue().getTargetId() + " Http status code: " + createdRelationshipWithResponse.getStatusCode())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipStringWithResponse -> System.out.println( "Created relationship: " + createdRelationshipStringWithResponse + " With HTTP status code: " + createdRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getRelationship() { digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class) .subscribe(retrievedRelationship -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationship.getId() + " from: " + retrievedRelationship.getSourceId() + " to: " + retrievedRelationship.getTargetId())); digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", String.class) .subscribe(retrievedRelationshipString -> System.out.println("Retrieved relationship: " + retrievedRelationshipString)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getRelationshipWithResponse() { digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipWithResponse -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationshipWithResponse.getValue().getId() + " from: " + retrievedRelationshipWithResponse.getValue().getSourceId() + " to: " + retrievedRelationshipWithResponse.getValue().getTargetId() + "HTTP status code: " + retrievedRelationshipWithResponse.getStatusCode())); digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", String.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipStringWithResponse -> System.out.println( "Retrieved relationship: " + retrievedRelationshipStringWithResponse + " HTTP status code: " + retrievedRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateRelationship() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationship( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateRelationshipWithResponse() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations(), new UpdateRelationshipOptions()) .subscribe(updateResponse -> System.out.println( "Relationship updated with status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationship() { digitalTwinsAsyncClient.deleteRelationship("myDigitalTwinId", "myRelationshipId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationshipWithResponse() { digitalTwinsAsyncClient.deleteRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", new DeleteRelationshipOptions()) .subscribe(deleteResponse -> System.out.println( "Deleted relationship with HTTP status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient * and {@link DigitalTwinsAsyncClient */ @Override public void listRelationships() { digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", BasicRelationship.class) .doOnNext(basicRel -> System.out.println("Retrieved relationship with Id: " + basicRel.getId())); digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", String.class) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship with Id: " + rel.getId())); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipId", String.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient */ @Override public void listIncomingRelationships() { digitalTwinsAsyncClient.listIncomingRelationships("myDigitalTwinId") .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); digitalTwinsAsyncClient.listIncomingRelationships( "myDigitalTwinId", new ListIncomingRelationshipsOptions()) .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createModels() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModels(Arrays.asList(model1, model2, model3)) .subscribe(createdModels -> createdModels.forEach(model -> System.out.println("Retrieved model with Id: " + model.getId()))); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createModelsWithResponse() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModelsWithResponse( Arrays.asList(model1, model2, model3), new CreateModelsOptions()) .subscribe(createdModels -> { System.out.println("Received a response with HTTP status code: " + createdModels.getStatusCode()); createdModels.getValue().forEach( model -> System.out.println("Retrieved model with Id: " + model.getId())); }); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getModel() { digitalTwinsAsyncClient.getModel("dtmi:samples:Building;1") .subscribe(model -> System.out.println("Retrieved model with Id: " + model.getId())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getModelWithResponse() { digitalTwinsAsyncClient.getModelWithResponse( "dtmi:samples:Building;1", new GetModelOptions()) .subscribe(modelWithResponse -> { System.out.println("Received HTTP response with status code: " + modelWithResponse.getStatusCode()); System.out.println("Retrieved model with Id: " + modelWithResponse.getValue().getId()); }); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient
class DigitalTwinsAsyncClientJavaDocCodeSnippets extends CodeSnippetBase { private final DigitalTwinsAsyncClient digitalTwinsAsyncClient; DigitalTwinsAsyncClientJavaDocCodeSnippets(){ digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); } public DigitalTwinsAsyncClient createDigitalTwinsAsyncClient() { String tenantId = getTenenatId(); String clientId = getClientId(); String clientSecret = getClientSecret(); String digitalTwinsEndpointUrl = getEndpointUrl(); DigitalTwinsAsyncClient digitalTwinsAsyncClient = new DigitalTwinsClientBuilder() .credential( new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build()) .endpoint(digitalTwinsEndpointUrl) .buildAsyncClient(); return digitalTwinsAsyncClient; } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwin(basicTwin.getId(), basicTwin, BasicDigitalTwin.class) .subscribe(response -> System.out.println("Created digital twin Id: " + response.getId())); String digitalTwinStringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwin("myDigitalTwinId", digitalTwinStringPayload, String.class) .subscribe(stringResponse -> System.out.println("Created digital twin: " + stringResponse)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwinWithResponse(){ DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicDigitalTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), basicDigitalTwin, BasicDigitalTwin.class, new CreateDigitalTwinOptions()) .subscribe(resultWithResponse -> System.out.println( "Response http status: " + resultWithResponse.getStatusCode() + " created digital twin Id: " + resultWithResponse.getValue().getId())); String stringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), stringPayload, String.class, new CreateDigitalTwinOptions()) .subscribe(stringWithResponse -> System.out.println( "Response http status: " + stringWithResponse.getStatusCode() + " created digital twin: " + stringWithResponse.getValue())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ public void getDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", BasicDigitalTwin.class) .subscribe( basicDigitalTwin -> System.out.println("Retrieved digital twin with Id: " + basicDigitalTwin.getId())); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", String.class) .subscribe(stringResult -> System.out.println("Retrieved digital twin: " + stringResult)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", BasicDigitalTwin.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin with Id: " + basicDigitalTwinWithResponse.getValue().getId() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", String.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin: " + basicDigitalTwinWithResponse.getValue() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwin( "myDigitalTwinId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwinWithResponse( "myDigitalTwinId", updateOperationUtility.getUpdateOperations(), new UpdateDigitalTwinOptions()) .subscribe(updateResponse -> System.out.println("Update completed with HTTP status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwin("myDigitalTwinId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwinWithResponse( "myDigitalTwinId", new DeleteDigitalTwinOptions()) .subscribe(deleteResponse -> System.out.println("Deleted digital twin. HTTP response status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createRelationshipWithResponse() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipWithResponse -> System.out.println( "Created relationship with Id: " + createdRelationshipWithResponse.getValue().getId() + " from: " + createdRelationshipWithResponse.getValue().getSourceId() + " to: " + createdRelationshipWithResponse.getValue().getTargetId() + " Http status code: " + createdRelationshipWithResponse.getStatusCode())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipStringWithResponse -> System.out.println( "Created relationship: " + createdRelationshipStringWithResponse + " With HTTP status code: " + createdRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getRelationship() { digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class) .subscribe(retrievedRelationship -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationship.getId() + " from: " + retrievedRelationship.getSourceId() + " to: " + retrievedRelationship.getTargetId())); digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", String.class) .subscribe(retrievedRelationshipString -> System.out.println("Retrieved relationship: " + retrievedRelationshipString)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getRelationshipWithResponse() { digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipWithResponse -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationshipWithResponse.getValue().getId() + " from: " + retrievedRelationshipWithResponse.getValue().getSourceId() + " to: " + retrievedRelationshipWithResponse.getValue().getTargetId() + "HTTP status code: " + retrievedRelationshipWithResponse.getStatusCode())); digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", String.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipStringWithResponse -> System.out.println( "Retrieved relationship: " + retrievedRelationshipStringWithResponse + " HTTP status code: " + retrievedRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateRelationship() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationship( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateRelationshipWithResponse() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations(), new UpdateRelationshipOptions()) .subscribe(updateResponse -> System.out.println( "Relationship updated with status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationship() { digitalTwinsAsyncClient.deleteRelationship("myDigitalTwinId", "myRelationshipId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationshipWithResponse() { digitalTwinsAsyncClient.deleteRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", new DeleteRelationshipOptions()) .subscribe(deleteResponse -> System.out.println( "Deleted relationship with HTTP status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient * and {@link DigitalTwinsAsyncClient */ @Override public void listRelationships() { digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", BasicRelationship.class) .doOnNext(basicRel -> System.out.println("Retrieved relationship with Id: " + basicRel.getId())); digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", String.class) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship with Id: " + rel.getId())); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipId", String.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient */ @Override public void listIncomingRelationships() { digitalTwinsAsyncClient.listIncomingRelationships("myDigitalTwinId") .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); digitalTwinsAsyncClient.listIncomingRelationships( "myDigitalTwinId", new ListIncomingRelationshipsOptions()) .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createModels() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModels(Arrays.asList(model1, model2, model3)) .subscribe(createdModels -> createdModels.forEach(model -> System.out.println("Retrieved model with Id: " + model.getId()))); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createModelsWithResponse() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModelsWithResponse( Arrays.asList(model1, model2, model3), new CreateModelsOptions()) .subscribe(createdModels -> { System.out.println("Received a response with HTTP status code: " + createdModels.getStatusCode()); createdModels.getValue().forEach( model -> System.out.println("Retrieved model with Id: " + model.getId())); }); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getModel() { digitalTwinsAsyncClient.getModel("dtmi:samples:Building;1") .subscribe(model -> System.out.println("Retrieved model with Id: " + model.getId())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getModelWithResponse() { digitalTwinsAsyncClient.getModelWithResponse( "dtmi:samples:Building;1", new GetModelOptions()) .subscribe(modelWithResponse -> { System.out.println("Received HTTP response with status code: " + modelWithResponse.getStatusCode()); System.out.println("Retrieved model with Id: " + modelWithResponse.getValue().getId()); }); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient
are these spaces?
public void createRelationship() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class) .subscribe(createdRelationship -> System.out.println( "Created relationship with Id: " + createdRelationship.getId() + " from: " + createdRelationship.getSourceId() + " to: " + createdRelationship.getTargetId())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class) .subscribe(createRelationshipString -> System.out.println("Created relationship: " + createRelationshipString)); }
"myRelationshipId",
public void createRelationship() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class) .subscribe(createdRelationship -> System.out.println( "Created relationship with Id: " + createdRelationship.getId() + " from: " + createdRelationship.getSourceId() + " to: " + createdRelationship.getTargetId())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class) .subscribe(createRelationshipString -> System.out.println("Created relationship: " + createRelationshipString)); }
class DigitalTwinsAsyncClientJavaDocCodeSnippets extends CodeSnippetBase { private final DigitalTwinsAsyncClient digitalTwinsAsyncClient; DigitalTwinsAsyncClientJavaDocCodeSnippets(){ digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); } public DigitalTwinsAsyncClient createDigitalTwinsAsyncClient() { String tenantId = getTenenatId(); String clientId = getClientId(); String clientSecret = getClientSecret(); String digitalTwinsEndpointUrl = getEndpointUrl(); DigitalTwinsAsyncClient digitalTwinsAsyncClient = new DigitalTwinsClientBuilder() .credential( new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build()) .endpoint(digitalTwinsEndpointUrl) .buildAsyncClient(); return digitalTwinsAsyncClient; } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwin(basicTwin.getId(), basicTwin, BasicDigitalTwin.class) .subscribe(response -> System.out.println("Created digital twin Id: " + response.getId())); String digitalTwinStringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwin("myDigitalTwinId", digitalTwinStringPayload, String.class) .subscribe(stringResponse -> System.out.println("Created digital twin: " + stringResponse)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwinWithResponse(){ DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicDigitalTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), basicDigitalTwin, BasicDigitalTwin.class, new CreateDigitalTwinOptions()) .subscribe(resultWithResponse -> System.out.println( "Response http status: " + resultWithResponse.getStatusCode() + " created digital twin Id: " + resultWithResponse.getValue().getId())); String stringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), stringPayload, String.class, new CreateDigitalTwinOptions()) .subscribe(stringWithResponse -> System.out.println( "Response http status: " + stringWithResponse.getStatusCode() + " created digital twin: " + stringWithResponse.getValue())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ public void getDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", BasicDigitalTwin.class) .subscribe( basicDigitalTwin -> System.out.println("Retrieved digital twin with Id: " + basicDigitalTwin.getId())); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", String.class) .subscribe(stringResult -> System.out.println("Retrieved digital twin: " + stringResult)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", BasicDigitalTwin.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin with Id: " + basicDigitalTwinWithResponse.getValue().getId() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", String.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin: " + basicDigitalTwinWithResponse.getValue() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwin( "myDigitalTwinId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwinWithResponse( "myDigitalTwinId", updateOperationUtility.getUpdateOperations(), new UpdateDigitalTwinOptions()) .subscribe(updateResponse -> System.out.println("Update completed with HTTP status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwin("myDigitalTwinId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwinWithResponse( "myDigitalTwinId", new DeleteDigitalTwinOptions()) .subscribe(deleteResponse -> System.out.println("Deleted digital twin. HTTP response status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createRelationshipWithResponse() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipWithResponse -> System.out.println( "Created relationship with Id: " + createdRelationshipWithResponse.getValue().getId() + " from: " + createdRelationshipWithResponse.getValue().getSourceId() + " to: " + createdRelationshipWithResponse.getValue().getTargetId() + " Http status code: " + createdRelationshipWithResponse.getStatusCode())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipStringWithResponse -> System.out.println( "Created relationship: " + createdRelationshipStringWithResponse + " With HTTP status code: " + createdRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getRelationship() { digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class) .subscribe(retrievedRelationship -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationship.getId() + " from: " + retrievedRelationship.getSourceId() + " to: " + retrievedRelationship.getTargetId())); digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", String.class) .subscribe(retrievedRelationshipString -> System.out.println("Retrieved relationship: " + retrievedRelationshipString)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getRelationshipWithResponse() { digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipWithResponse -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationshipWithResponse.getValue().getId() + " from: " + retrievedRelationshipWithResponse.getValue().getSourceId() + " to: " + retrievedRelationshipWithResponse.getValue().getTargetId() + "HTTP status code: " + retrievedRelationshipWithResponse.getStatusCode())); digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", String.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipStringWithResponse -> System.out.println( "Retrieved relationship: " + retrievedRelationshipStringWithResponse + " HTTP status code: " + retrievedRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateRelationship() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationship( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateRelationshipWithResponse() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations(), new UpdateRelationshipOptions()) .subscribe(updateResponse -> System.out.println( "Relationship updated with status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationship() { digitalTwinsAsyncClient.deleteRelationship("myDigitalTwinId", "myRelationshipId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationshipWithResponse() { digitalTwinsAsyncClient.deleteRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", new DeleteRelationshipOptions()) .subscribe(deleteResponse -> System.out.println( "Deleted relationship with HTTP status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient * and {@link DigitalTwinsAsyncClient */ @Override public void listRelationships() { digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", BasicRelationship.class) .doOnNext(basicRel -> System.out.println("Retrieved relationship with Id: " + basicRel.getId())); digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", String.class) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship with Id: " + rel.getId())); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipId", String.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient */ @Override public void listIncomingRelationships() { digitalTwinsAsyncClient.listIncomingRelationships("myDigitalTwinId") .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); digitalTwinsAsyncClient.listIncomingRelationships( "myDigitalTwinId", new ListIncomingRelationshipsOptions()) .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createModels() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModels(Arrays.asList(model1, model2, model3)) .subscribe(createdModels -> createdModels.forEach(model -> System.out.println("Retrieved model with Id: " + model.getId()))); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createModelsWithResponse() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModelsWithResponse( Arrays.asList(model1, model2, model3), new CreateModelsOptions()) .subscribe(createdModels -> { System.out.println("Received a response with HTTP status code: " + createdModels.getStatusCode()); createdModels.getValue().forEach( model -> System.out.println("Retrieved model with Id: " + model.getId())); }); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getModel() { digitalTwinsAsyncClient.getModel("dtmi:samples:Building;1") .subscribe(model -> System.out.println("Retrieved model with Id: " + model.getId())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getModelWithResponse() { digitalTwinsAsyncClient.getModelWithResponse( "dtmi:samples:Building;1", new GetModelOptions()) .subscribe(modelWithResponse -> { System.out.println("Received HTTP response with status code: " + modelWithResponse.getStatusCode()); System.out.println("Retrieved model with Id: " + modelWithResponse.getValue().getId()); }); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient
class DigitalTwinsAsyncClientJavaDocCodeSnippets extends CodeSnippetBase { private final DigitalTwinsAsyncClient digitalTwinsAsyncClient; DigitalTwinsAsyncClientJavaDocCodeSnippets(){ digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); } public DigitalTwinsAsyncClient createDigitalTwinsAsyncClient() { String tenantId = getTenenatId(); String clientId = getClientId(); String clientSecret = getClientSecret(); String digitalTwinsEndpointUrl = getEndpointUrl(); DigitalTwinsAsyncClient digitalTwinsAsyncClient = new DigitalTwinsClientBuilder() .credential( new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build()) .endpoint(digitalTwinsEndpointUrl) .buildAsyncClient(); return digitalTwinsAsyncClient; } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwin(basicTwin.getId(), basicTwin, BasicDigitalTwin.class) .subscribe(response -> System.out.println("Created digital twin Id: " + response.getId())); String digitalTwinStringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwin("myDigitalTwinId", digitalTwinStringPayload, String.class) .subscribe(stringResponse -> System.out.println("Created digital twin: " + stringResponse)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwinWithResponse(){ DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicDigitalTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), basicDigitalTwin, BasicDigitalTwin.class, new CreateDigitalTwinOptions()) .subscribe(resultWithResponse -> System.out.println( "Response http status: " + resultWithResponse.getStatusCode() + " created digital twin Id: " + resultWithResponse.getValue().getId())); String stringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), stringPayload, String.class, new CreateDigitalTwinOptions()) .subscribe(stringWithResponse -> System.out.println( "Response http status: " + stringWithResponse.getStatusCode() + " created digital twin: " + stringWithResponse.getValue())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ public void getDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", BasicDigitalTwin.class) .subscribe( basicDigitalTwin -> System.out.println("Retrieved digital twin with Id: " + basicDigitalTwin.getId())); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", String.class) .subscribe(stringResult -> System.out.println("Retrieved digital twin: " + stringResult)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", BasicDigitalTwin.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin with Id: " + basicDigitalTwinWithResponse.getValue().getId() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", String.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin: " + basicDigitalTwinWithResponse.getValue() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwin( "myDigitalTwinId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwinWithResponse( "myDigitalTwinId", updateOperationUtility.getUpdateOperations(), new UpdateDigitalTwinOptions()) .subscribe(updateResponse -> System.out.println("Update completed with HTTP status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwin("myDigitalTwinId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwinWithResponse( "myDigitalTwinId", new DeleteDigitalTwinOptions()) .subscribe(deleteResponse -> System.out.println("Deleted digital twin. HTTP response status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createRelationshipWithResponse() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipWithResponse -> System.out.println( "Created relationship with Id: " + createdRelationshipWithResponse.getValue().getId() + " from: " + createdRelationshipWithResponse.getValue().getSourceId() + " to: " + createdRelationshipWithResponse.getValue().getTargetId() + " Http status code: " + createdRelationshipWithResponse.getStatusCode())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipStringWithResponse -> System.out.println( "Created relationship: " + createdRelationshipStringWithResponse + " With HTTP status code: " + createdRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getRelationship() { digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class) .subscribe(retrievedRelationship -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationship.getId() + " from: " + retrievedRelationship.getSourceId() + " to: " + retrievedRelationship.getTargetId())); digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", String.class) .subscribe(retrievedRelationshipString -> System.out.println("Retrieved relationship: " + retrievedRelationshipString)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getRelationshipWithResponse() { digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipWithResponse -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationshipWithResponse.getValue().getId() + " from: " + retrievedRelationshipWithResponse.getValue().getSourceId() + " to: " + retrievedRelationshipWithResponse.getValue().getTargetId() + "HTTP status code: " + retrievedRelationshipWithResponse.getStatusCode())); digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", String.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipStringWithResponse -> System.out.println( "Retrieved relationship: " + retrievedRelationshipStringWithResponse + " HTTP status code: " + retrievedRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateRelationship() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationship( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateRelationshipWithResponse() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations(), new UpdateRelationshipOptions()) .subscribe(updateResponse -> System.out.println( "Relationship updated with status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationship() { digitalTwinsAsyncClient.deleteRelationship("myDigitalTwinId", "myRelationshipId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationshipWithResponse() { digitalTwinsAsyncClient.deleteRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", new DeleteRelationshipOptions()) .subscribe(deleteResponse -> System.out.println( "Deleted relationship with HTTP status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient * and {@link DigitalTwinsAsyncClient */ @Override public void listRelationships() { digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", BasicRelationship.class) .doOnNext(basicRel -> System.out.println("Retrieved relationship with Id: " + basicRel.getId())); digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", String.class) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship with Id: " + rel.getId())); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipId", String.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient */ @Override public void listIncomingRelationships() { digitalTwinsAsyncClient.listIncomingRelationships("myDigitalTwinId") .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); digitalTwinsAsyncClient.listIncomingRelationships( "myDigitalTwinId", new ListIncomingRelationshipsOptions()) .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createModels() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModels(Arrays.asList(model1, model2, model3)) .subscribe(createdModels -> createdModels.forEach(model -> System.out.println("Retrieved model with Id: " + model.getId()))); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createModelsWithResponse() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModelsWithResponse( Arrays.asList(model1, model2, model3), new CreateModelsOptions()) .subscribe(createdModels -> { System.out.println("Received a response with HTTP status code: " + createdModels.getStatusCode()); createdModels.getValue().forEach( model -> System.out.println("Retrieved model with Id: " + model.getId())); }); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getModel() { digitalTwinsAsyncClient.getModel("dtmi:samples:Building;1") .subscribe(model -> System.out.println("Retrieved model with Id: " + model.getId())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getModelWithResponse() { digitalTwinsAsyncClient.getModelWithResponse( "dtmi:samples:Building;1", new GetModelOptions()) .subscribe(modelWithResponse -> { System.out.println("Received HTTP response with status code: " + modelWithResponse.getStatusCode()); System.out.println("Retrieved model with Id: " + modelWithResponse.getValue().getId()); }); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient
tabs
public void createRelationship() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class) .subscribe(createdRelationship -> System.out.println( "Created relationship with Id: " + createdRelationship.getId() + " from: " + createdRelationship.getSourceId() + " to: " + createdRelationship.getTargetId())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class) .subscribe(createRelationshipString -> System.out.println("Created relationship: " + createRelationshipString)); }
"myRelationshipId",
public void createRelationship() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class) .subscribe(createdRelationship -> System.out.println( "Created relationship with Id: " + createdRelationship.getId() + " from: " + createdRelationship.getSourceId() + " to: " + createdRelationship.getTargetId())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationship( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class) .subscribe(createRelationshipString -> System.out.println("Created relationship: " + createRelationshipString)); }
class DigitalTwinsAsyncClientJavaDocCodeSnippets extends CodeSnippetBase { private final DigitalTwinsAsyncClient digitalTwinsAsyncClient; DigitalTwinsAsyncClientJavaDocCodeSnippets(){ digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); } public DigitalTwinsAsyncClient createDigitalTwinsAsyncClient() { String tenantId = getTenenatId(); String clientId = getClientId(); String clientSecret = getClientSecret(); String digitalTwinsEndpointUrl = getEndpointUrl(); DigitalTwinsAsyncClient digitalTwinsAsyncClient = new DigitalTwinsClientBuilder() .credential( new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build()) .endpoint(digitalTwinsEndpointUrl) .buildAsyncClient(); return digitalTwinsAsyncClient; } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwin(basicTwin.getId(), basicTwin, BasicDigitalTwin.class) .subscribe(response -> System.out.println("Created digital twin Id: " + response.getId())); String digitalTwinStringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwin("myDigitalTwinId", digitalTwinStringPayload, String.class) .subscribe(stringResponse -> System.out.println("Created digital twin: " + stringResponse)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwinWithResponse(){ DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicDigitalTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), basicDigitalTwin, BasicDigitalTwin.class, new CreateDigitalTwinOptions()) .subscribe(resultWithResponse -> System.out.println( "Response http status: " + resultWithResponse.getStatusCode() + " created digital twin Id: " + resultWithResponse.getValue().getId())); String stringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), stringPayload, String.class, new CreateDigitalTwinOptions()) .subscribe(stringWithResponse -> System.out.println( "Response http status: " + stringWithResponse.getStatusCode() + " created digital twin: " + stringWithResponse.getValue())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ public void getDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", BasicDigitalTwin.class) .subscribe( basicDigitalTwin -> System.out.println("Retrieved digital twin with Id: " + basicDigitalTwin.getId())); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", String.class) .subscribe(stringResult -> System.out.println("Retrieved digital twin: " + stringResult)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", BasicDigitalTwin.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin with Id: " + basicDigitalTwinWithResponse.getValue().getId() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", String.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin: " + basicDigitalTwinWithResponse.getValue() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwin( "myDigitalTwinId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwinWithResponse( "myDigitalTwinId", updateOperationUtility.getUpdateOperations(), new UpdateDigitalTwinOptions()) .subscribe(updateResponse -> System.out.println("Update completed with HTTP status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwin("myDigitalTwinId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwinWithResponse( "myDigitalTwinId", new DeleteDigitalTwinOptions()) .subscribe(deleteResponse -> System.out.println("Deleted digital twin. HTTP response status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createRelationshipWithResponse() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipWithResponse -> System.out.println( "Created relationship with Id: " + createdRelationshipWithResponse.getValue().getId() + " from: " + createdRelationshipWithResponse.getValue().getSourceId() + " to: " + createdRelationshipWithResponse.getValue().getTargetId() + " Http status code: " + createdRelationshipWithResponse.getStatusCode())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipStringWithResponse -> System.out.println( "Created relationship: " + createdRelationshipStringWithResponse + " With HTTP status code: " + createdRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getRelationship() { digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class) .subscribe(retrievedRelationship -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationship.getId() + " from: " + retrievedRelationship.getSourceId() + " to: " + retrievedRelationship.getTargetId())); digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", String.class) .subscribe(retrievedRelationshipString -> System.out.println("Retrieved relationship: " + retrievedRelationshipString)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getRelationshipWithResponse() { digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipWithResponse -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationshipWithResponse.getValue().getId() + " from: " + retrievedRelationshipWithResponse.getValue().getSourceId() + " to: " + retrievedRelationshipWithResponse.getValue().getTargetId() + "HTTP status code: " + retrievedRelationshipWithResponse.getStatusCode())); digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", String.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipStringWithResponse -> System.out.println( "Retrieved relationship: " + retrievedRelationshipStringWithResponse + " HTTP status code: " + retrievedRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateRelationship() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationship( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateRelationshipWithResponse() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations(), new UpdateRelationshipOptions()) .subscribe(updateResponse -> System.out.println( "Relationship updated with status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationship() { digitalTwinsAsyncClient.deleteRelationship("myDigitalTwinId", "myRelationshipId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationshipWithResponse() { digitalTwinsAsyncClient.deleteRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", new DeleteRelationshipOptions()) .subscribe(deleteResponse -> System.out.println( "Deleted relationship with HTTP status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient * and {@link DigitalTwinsAsyncClient */ @Override public void listRelationships() { digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", BasicRelationship.class) .doOnNext(basicRel -> System.out.println("Retrieved relationship with Id: " + basicRel.getId())); digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", String.class) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship with Id: " + rel.getId())); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipId", String.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient */ @Override public void listIncomingRelationships() { digitalTwinsAsyncClient.listIncomingRelationships("myDigitalTwinId") .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); digitalTwinsAsyncClient.listIncomingRelationships( "myDigitalTwinId", new ListIncomingRelationshipsOptions()) .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createModels() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModels(Arrays.asList(model1, model2, model3)) .subscribe(createdModels -> createdModels.forEach(model -> System.out.println("Retrieved model with Id: " + model.getId()))); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createModelsWithResponse() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModelsWithResponse( Arrays.asList(model1, model2, model3), new CreateModelsOptions()) .subscribe(createdModels -> { System.out.println("Received a response with HTTP status code: " + createdModels.getStatusCode()); createdModels.getValue().forEach( model -> System.out.println("Retrieved model with Id: " + model.getId())); }); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getModel() { digitalTwinsAsyncClient.getModel("dtmi:samples:Building;1") .subscribe(model -> System.out.println("Retrieved model with Id: " + model.getId())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getModelWithResponse() { digitalTwinsAsyncClient.getModelWithResponse( "dtmi:samples:Building;1", new GetModelOptions()) .subscribe(modelWithResponse -> { System.out.println("Received HTTP response with status code: " + modelWithResponse.getStatusCode()); System.out.println("Retrieved model with Id: " + modelWithResponse.getValue().getId()); }); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient
class DigitalTwinsAsyncClientJavaDocCodeSnippets extends CodeSnippetBase { private final DigitalTwinsAsyncClient digitalTwinsAsyncClient; DigitalTwinsAsyncClientJavaDocCodeSnippets(){ digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); } public DigitalTwinsAsyncClient createDigitalTwinsAsyncClient() { String tenantId = getTenenatId(); String clientId = getClientId(); String clientSecret = getClientSecret(); String digitalTwinsEndpointUrl = getEndpointUrl(); DigitalTwinsAsyncClient digitalTwinsAsyncClient = new DigitalTwinsClientBuilder() .credential( new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build()) .endpoint(digitalTwinsEndpointUrl) .buildAsyncClient(); return digitalTwinsAsyncClient; } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwin(basicTwin.getId(), basicTwin, BasicDigitalTwin.class) .subscribe(response -> System.out.println("Created digital twin Id: " + response.getId())); String digitalTwinStringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwin("myDigitalTwinId", digitalTwinStringPayload, String.class) .subscribe(stringResponse -> System.out.println("Created digital twin: " + stringResponse)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createDigitalTwinWithResponse(){ DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); String modelId = "dtmi:samples:Building;1"; BasicDigitalTwin basicDigitalTwin = new BasicDigitalTwin("myDigitalTwinId") .setMetadata( new DigitalTwinMetadata() .setModelId(modelId) ); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), basicDigitalTwin, BasicDigitalTwin.class, new CreateDigitalTwinOptions()) .subscribe(resultWithResponse -> System.out.println( "Response http status: " + resultWithResponse.getStatusCode() + " created digital twin Id: " + resultWithResponse.getValue().getId())); String stringPayload = getDigitalTwinPayload(); digitalTwinsAsyncClient.createDigitalTwinWithResponse( basicDigitalTwin.getId(), stringPayload, String.class, new CreateDigitalTwinOptions()) .subscribe(stringWithResponse -> System.out.println( "Response http status: " + stringWithResponse.getStatusCode() + " created digital twin: " + stringWithResponse.getValue())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ public void getDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", BasicDigitalTwin.class) .subscribe( basicDigitalTwin -> System.out.println("Retrieved digital twin with Id: " + basicDigitalTwin.getId())); digitalTwinsAsyncClient.getDigitalTwin("myDigitalTwinId", String.class) .subscribe(stringResult -> System.out.println("Retrieved digital twin: " + stringResult)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", BasicDigitalTwin.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin with Id: " + basicDigitalTwinWithResponse.getValue().getId() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); digitalTwinsAsyncClient.getDigitalTwinWithResponse( "myDigitalTwinId", String.class, new GetDigitalTwinOptions()) .subscribe( basicDigitalTwinWithResponse -> System.out.println( "Retrieved digital twin: " + basicDigitalTwinWithResponse.getValue() + " Http Status Code: " + basicDigitalTwinWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwin( "myDigitalTwinId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("Prop1", "newValue"); digitalTwinsAsyncClient.updateDigitalTwinWithResponse( "myDigitalTwinId", updateOperationUtility.getUpdateOperations(), new UpdateDigitalTwinOptions()) .subscribe(updateResponse -> System.out.println("Update completed with HTTP status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwin() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwin("myDigitalTwinId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteDigitalTwinWithResponse() { DigitalTwinsAsyncClient digitalTwinsAsyncClient = createDigitalTwinsAsyncClient(); digitalTwinsAsyncClient.deleteDigitalTwinWithResponse( "myDigitalTwinId", new DeleteDigitalTwinOptions()) .subscribe(deleteResponse -> System.out.println("Deleted digital twin. HTTP response status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createRelationshipWithResponse() { BasicRelationship buildingToFloorBasicRelationship = new BasicRelationship( "myRelationshipId", "mySourceDigitalTwinId", "myTargetDigitalTwinId", "contains") .addCustomProperty("Prop1", "Prop1 value") .addCustomProperty("Prop2", 6); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", buildingToFloorBasicRelationship, BasicRelationship.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipWithResponse -> System.out.println( "Created relationship with Id: " + createdRelationshipWithResponse.getValue().getId() + " from: " + createdRelationshipWithResponse.getValue().getSourceId() + " to: " + createdRelationshipWithResponse.getValue().getTargetId() + " Http status code: " + createdRelationshipWithResponse.getStatusCode())); String relationshipPayload = getRelationshipPayload(); digitalTwinsAsyncClient.createRelationshipWithResponse( "mySourceDigitalTwinId", "myRelationshipId", relationshipPayload, String.class, new CreateRelationshipOptions()) .subscribe(createdRelationshipStringWithResponse -> System.out.println( "Created relationship: " + createdRelationshipStringWithResponse + " With HTTP status code: " + createdRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getRelationship() { digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class) .subscribe(retrievedRelationship -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationship.getId() + " from: " + retrievedRelationship.getSourceId() + " to: " + retrievedRelationship.getTargetId())); digitalTwinsAsyncClient.getRelationship( "myDigitalTwinId", "myRelationshipName", String.class) .subscribe(retrievedRelationshipString -> System.out.println("Retrieved relationship: " + retrievedRelationshipString)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getRelationshipWithResponse() { digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipWithResponse -> System.out.println( "Retrieved relationship with Id: " + retrievedRelationshipWithResponse.getValue().getId() + " from: " + retrievedRelationshipWithResponse.getValue().getSourceId() + " to: " + retrievedRelationshipWithResponse.getValue().getTargetId() + "HTTP status code: " + retrievedRelationshipWithResponse.getStatusCode())); digitalTwinsAsyncClient.getRelationshipWithResponse( "myDigitalTwinId", "myRelationshipName", String.class, new GetRelationshipOptions()) .subscribe(retrievedRelationshipStringWithResponse -> System.out.println( "Retrieved relationship: " + retrievedRelationshipStringWithResponse + " HTTP status code: " + retrievedRelationshipStringWithResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void updateRelationship() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationship( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations()) .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void updateRelationshipWithResponse() { UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility(); updateOperationUtility.appendReplaceOperation("/relationshipProperty1", "new property value"); digitalTwinsAsyncClient.updateRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", updateOperationUtility.getUpdateOperations(), new UpdateRelationshipOptions()) .subscribe(updateResponse -> System.out.println( "Relationship updated with status code: " + updateResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationship() { digitalTwinsAsyncClient.deleteRelationship("myDigitalTwinId", "myRelationshipId") .subscribe(); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void deleteRelationshipWithResponse() { digitalTwinsAsyncClient.deleteRelationshipWithResponse( "myDigitalTwinId", "myRelationshipId", new DeleteRelationshipOptions()) .subscribe(deleteResponse -> System.out.println( "Deleted relationship with HTTP status code: " + deleteResponse.getStatusCode())); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient * and {@link DigitalTwinsAsyncClient */ @Override public void listRelationships() { digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", BasicRelationship.class) .doOnNext(basicRel -> System.out.println("Retrieved relationship with Id: " + basicRel.getId())); digitalTwinsAsyncClient.listRelationships("myDigitalTwinId", String.class) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipName", BasicRelationship.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship with Id: " + rel.getId())); digitalTwinsAsyncClient.listRelationships( "myDigitalTwinId", "myRelationshipId", String.class, new ListRelationshipsOptions()) .doOnNext(rel -> System.out.println("Retrieved relationship: " + rel)); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient */ @Override public void listIncomingRelationships() { digitalTwinsAsyncClient.listIncomingRelationships("myDigitalTwinId") .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); digitalTwinsAsyncClient.listIncomingRelationships( "myDigitalTwinId", new ListIncomingRelationshipsOptions()) .doOnNext(incomingRel -> System.out.println( "Retrieved relationship with Id: " + incomingRel.getRelationshipId() + " from: " + incomingRel.getSourceId() + " to: myDigitalTwinId")) .subscribe(); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void createModels() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModels(Arrays.asList(model1, model2, model3)) .subscribe(createdModels -> createdModels.forEach(model -> System.out.println("Retrieved model with Id: " + model.getId()))); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void createModelsWithResponse() { String model1 = loadModelFromFile("model1"); String model2 = loadModelFromFile("model2"); String model3 = loadModelFromFile("model3"); digitalTwinsAsyncClient.createModelsWithResponse( Arrays.asList(model1, model2, model3), new CreateModelsOptions()) .subscribe(createdModels -> { System.out.println("Received a response with HTTP status code: " + createdModels.getStatusCode()); createdModels.getValue().forEach( model -> System.out.println("Retrieved model with Id: " + model.getId())); }); } /** * Generates code samples for using {@link DigitalTwinsAsyncClient */ @Override public void getModel() { digitalTwinsAsyncClient.getModel("dtmi:samples:Building;1") .subscribe(model -> System.out.println("Retrieved model with Id: " + model.getId())); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient */ @Override public void getModelWithResponse() { digitalTwinsAsyncClient.getModelWithResponse( "dtmi:samples:Building;1", new GetModelOptions()) .subscribe(modelWithResponse -> { System.out.println("Received HTTP response with status code: " + modelWithResponse.getStatusCode()); System.out.println("Retrieved model with Id: " + modelWithResponse.getValue().getId()); }); } /** * Generates code samples for using * {@link DigitalTwinsAsyncClient * {@link DigitalTwinsAsyncClient
nice :clap:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Option)) { return false; } Option<?> other = (Option<?>) obj; if (this.isInitialized ^ other.isInitialized) { return false; } return Objects.equals(value, other.value); }
}
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Option)) { return false; } Option<?> other = (Option<?>) obj; if (this.isInitialized ^ other.isInitialized) { return false; } return Objects.equals(value, other.value); }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if a value has been initialized, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The {@code null} (null-value) or non-null-value that the {@link Option} * is initialized with. * @throws NoSuchElementException thrown if the {@link Option} is in no-value state. */ public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value initialized"); } return this.value; } /** * Indicates whether some other object is "equal to" this Option. The * other object is considered equal if: * <ul> * <li>it is also an {@code Option} and; * <li>both instances are not initialized or; * <li>both instances are initialized and values are "equal to" each other via {@code equals()}. * </ul> * * @param obj an object to be tested for equality * @return {code true} if the other object is "equal to" this object otherwise {@code false} */ @Override /** * Returns hash code of the value this Option is initialized with or -1 if in * uninitialized state. * <p> * The value 0 will be returned when initialized with {@code null}. * </p> * @return hash code of the value this Option is initialized with or -1 if in * uninitialized state. */ @Override public int hashCode() { if (!this.isInitialized) { return -1; } return Objects.hashCode(value); } private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if a value has been initialized, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The {@code null} (null-value) or non-null-value that the {@link Option} * is initialized with. * @throws NoSuchElementException thrown if the {@link Option} is in no-value state. */ public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value initialized"); } return this.value; } /** * Indicates whether some other object is "equal to" this Option. The * other object is considered equal if: * <ul> * <li>it is also an {@code Option} and; * <li>both instances are not initialized or; * <li>both instances are initialized and values are "equal to" each other via {@code equals()}. * </ul> * * @param obj an object to be tested for equality * @return {code true} if the other object is "equal to" this object otherwise {@code false} */ @Override /** * Returns hash code of the value this Option is initialized with or -1 if in * uninitialized state. * <p> * The value 0 will be returned when initialized with {@code null}. * </p> * @return hash code of the value this Option is initialized with or -1 if in * uninitialized state. */ @Override public int hashCode() { if (!this.isInitialized) { return -1; } return Objects.hashCode(value); } private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
not sure but probably static + DCL is safe in latest version of java, I remember spot bug alerting DCL in the past. jfyi, there is also an init-on-demand-holder [pattern](https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom) for these cases which won't require an explicit lock.
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (DEFAULT_SERIALIZER == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (DEFAULT_SERIALIZER == null) { DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(); } } } DEFAULT_SERIALIZER.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
if (DEFAULT_SERIALIZER == null) {
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (defaultSerializer == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (defaultSerializer == null) { defaultSerializer = JsonSerializerProviders.createInstance(); } } } defaultSerializer.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
class JsonPatchDocument { private static final Object SERIALIZER_INSTANTIATION_SYNCHRONIZER = new Object(); private static JsonSerializer DEFAULT_SERIALIZER; @JsonIgnore private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class); @JsonValue private final List<JsonPatchOperation> operations; @JsonIgnore private final JsonSerializer serializer; /** * Creates a new JSON Patch document. */ public JsonPatchDocument() { this(null); } /** * Creates a new JSON Patch document. * <p> * If {@code serializer} isn't specified {@link JacksonAdapter} will be used. * * @param serializer The {@link JsonSerializer} that will be used to serialize patch operation values. */ public JsonPatchDocument(JsonSerializer serializer) { this.operations = new ArrayList<>(); this.serializer = serializer; } List<JsonPatchOperation> getOperations() { return new ArrayList<>(operations); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAdd * * @param path The path to apply the addition. * @param value The value that will be serialized and added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAdd(String path, Object value) { return appendAddInternal(path, () -> serializeValue(value)); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAddRaw * * @param path The path to apply the addition. * @param rawJson The raw JSON value that will be added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAddRaw(String path, String rawJson) { return appendAddInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendAddInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.ADD, null, path, jsonSupplier.get()); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplace * * @param path The path to replace. * @param value The value will be serialized and used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplace(String path, Object value) { return appendReplaceInternal(path, () -> serializeValue(value)); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplaceRaw * * @param path The path to replace. * @param rawJson The raw JSON value that will be used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplaceRaw(String path, String rawJson) { return appendReplaceInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendReplaceInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REPLACE, null, path, jsonSupplier.get()); } /** * Appends a "copy" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendCopy * * @param from The path to copy from. * @param path The path to copy to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendCopy(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.COPY, from, path, Option.uninitialized()); } /** * Appends a "move" operation to this JSON Patch document. * <p> * For the operation to be successful {@code path} cannot be a child node of {@code from}. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendMove * * @param from The path to move from. * @param path The path to move to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendMove(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.MOVE, from, path, Option.uninitialized()); } /** * Appends a "remove" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendRemove * * @param path The path to remove. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendRemove(String path) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REMOVE, null, path, Option.uninitialized()); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTest * * @param path The path to test. * @param value The value that will be serialized and used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTest(String path, Object value) { return appendTestInternal(path, () -> serializeValue(value)); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTestRaw * * @param path The path to test. * @param rawJson The raw JSON value that will be used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTestRaw(String path, String rawJson) { return appendTestInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendTestInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.TEST, null, path, jsonSupplier.get()); } private JsonPatchDocument appendOperation(JsonPatchOperationKind operationKind, String from, String path, Option<String> optionalValue) { operations.add(new JsonPatchOperation(operationKind, from, path, optionalValue)); return this; } /** * Gets a formatted JSON string representation of this JSON Patch document. * * @return The formatted JSON String representing this JSON Patch docuemnt. */ @Override public String toString() { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < operations.size(); i++) { if (i > 0) { builder.append(","); } operations.get(i).buildString(builder); } return builder.append("]").toString(); } }
class JsonPatchDocument { private static final Object SERIALIZER_INSTANTIATION_SYNCHRONIZER = new Object(); private static volatile JsonSerializer defaultSerializer; @JsonIgnore private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class); @JsonValue private final List<JsonPatchOperation> operations; @JsonIgnore private final JsonSerializer serializer; /** * Creates a new JSON Patch document. */ public JsonPatchDocument() { this(null); } /** * Creates a new JSON Patch document. * <p> * If {@code serializer} isn't specified {@link JacksonAdapter} will be used. * * @param serializer The {@link JsonSerializer} that will be used to serialize patch operation values. */ public JsonPatchDocument(JsonSerializer serializer) { this.operations = new ArrayList<>(); this.serializer = serializer; } List<JsonPatchOperation> getOperations() { return new ArrayList<>(operations); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAdd * * @param path The path to apply the addition. * @param value The value that will be serialized and added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAdd(String path, Object value) { return appendAddInternal(path, serializeValue(value)); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAddRaw * * @param path The path to apply the addition. * @param rawJson The raw JSON value that will be added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAddRaw(String path, String rawJson) { return appendAddInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendAddInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.ADD, null, path, rawJsonOption); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplace * * @param path The path to replace. * @param value The value will be serialized and used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplace(String path, Object value) { return appendReplaceInternal(path, serializeValue(value)); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplaceRaw * * @param path The path to replace. * @param rawJson The raw JSON value that will be used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplaceRaw(String path, String rawJson) { return appendReplaceInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendReplaceInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REPLACE, null, path, rawJsonOption); } /** * Appends a "copy" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendCopy * * @param from The path to copy from. * @param path The path to copy to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendCopy(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.COPY, from, path, Option.uninitialized()); } /** * Appends a "move" operation to this JSON Patch document. * <p> * For the operation to be successful {@code path} cannot be a child node of {@code from}. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendMove * * @param from The path to move from. * @param path The path to move to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendMove(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.MOVE, from, path, Option.uninitialized()); } /** * Appends a "remove" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendRemove * * @param path The path to remove. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendRemove(String path) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REMOVE, null, path, Option.uninitialized()); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTest * * @param path The path to test. * @param value The value that will be serialized and used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTest(String path, Object value) { return appendTestInternal(path, serializeValue(value)); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTestRaw * * @param path The path to test. * @param rawJson The raw JSON value that will be used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTestRaw(String path, String rawJson) { return appendTestInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendTestInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.TEST, null, path, rawJsonOption); } private JsonPatchDocument appendOperation(JsonPatchOperationKind operationKind, String from, String path, Option<String> optionalValue) { operations.add(new JsonPatchOperation(operationKind, from, path, optionalValue)); return this; } /** * Gets a formatted JSON string representation of this JSON Patch document. * * @return The formatted JSON String representing this JSON Patch docuemnt. */ @Override public String toString() { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < operations.size(); i++) { if (i > 0) { builder.append(","); } operations.get(i).buildString(builder); } return builder.append("]").toString(); } }
Yeah, I agree that if we want lazy loading use holder pattern. DCL with static might not be safe. If this is a constant then, it should be initialized by the classloader in a static block.
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (DEFAULT_SERIALIZER == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (DEFAULT_SERIALIZER == null) { DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(); } } } DEFAULT_SERIALIZER.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
if (DEFAULT_SERIALIZER == null) {
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (defaultSerializer == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (defaultSerializer == null) { defaultSerializer = JsonSerializerProviders.createInstance(); } } } defaultSerializer.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
class JsonPatchDocument { private static final Object SERIALIZER_INSTANTIATION_SYNCHRONIZER = new Object(); private static JsonSerializer DEFAULT_SERIALIZER; @JsonIgnore private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class); @JsonValue private final List<JsonPatchOperation> operations; @JsonIgnore private final JsonSerializer serializer; /** * Creates a new JSON Patch document. */ public JsonPatchDocument() { this(null); } /** * Creates a new JSON Patch document. * <p> * If {@code serializer} isn't specified {@link JacksonAdapter} will be used. * * @param serializer The {@link JsonSerializer} that will be used to serialize patch operation values. */ public JsonPatchDocument(JsonSerializer serializer) { this.operations = new ArrayList<>(); this.serializer = serializer; } List<JsonPatchOperation> getOperations() { return new ArrayList<>(operations); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAdd * * @param path The path to apply the addition. * @param value The value that will be serialized and added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAdd(String path, Object value) { return appendAddInternal(path, () -> serializeValue(value)); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAddRaw * * @param path The path to apply the addition. * @param rawJson The raw JSON value that will be added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAddRaw(String path, String rawJson) { return appendAddInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendAddInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.ADD, null, path, jsonSupplier.get()); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplace * * @param path The path to replace. * @param value The value will be serialized and used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplace(String path, Object value) { return appendReplaceInternal(path, () -> serializeValue(value)); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplaceRaw * * @param path The path to replace. * @param rawJson The raw JSON value that will be used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplaceRaw(String path, String rawJson) { return appendReplaceInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendReplaceInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REPLACE, null, path, jsonSupplier.get()); } /** * Appends a "copy" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendCopy * * @param from The path to copy from. * @param path The path to copy to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendCopy(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.COPY, from, path, Option.uninitialized()); } /** * Appends a "move" operation to this JSON Patch document. * <p> * For the operation to be successful {@code path} cannot be a child node of {@code from}. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendMove * * @param from The path to move from. * @param path The path to move to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendMove(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.MOVE, from, path, Option.uninitialized()); } /** * Appends a "remove" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendRemove * * @param path The path to remove. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendRemove(String path) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REMOVE, null, path, Option.uninitialized()); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTest * * @param path The path to test. * @param value The value that will be serialized and used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTest(String path, Object value) { return appendTestInternal(path, () -> serializeValue(value)); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTestRaw * * @param path The path to test. * @param rawJson The raw JSON value that will be used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTestRaw(String path, String rawJson) { return appendTestInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendTestInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.TEST, null, path, jsonSupplier.get()); } private JsonPatchDocument appendOperation(JsonPatchOperationKind operationKind, String from, String path, Option<String> optionalValue) { operations.add(new JsonPatchOperation(operationKind, from, path, optionalValue)); return this; } /** * Gets a formatted JSON string representation of this JSON Patch document. * * @return The formatted JSON String representing this JSON Patch docuemnt. */ @Override public String toString() { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < operations.size(); i++) { if (i > 0) { builder.append(","); } operations.get(i).buildString(builder); } return builder.append("]").toString(); } }
class JsonPatchDocument { private static final Object SERIALIZER_INSTANTIATION_SYNCHRONIZER = new Object(); private static volatile JsonSerializer defaultSerializer; @JsonIgnore private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class); @JsonValue private final List<JsonPatchOperation> operations; @JsonIgnore private final JsonSerializer serializer; /** * Creates a new JSON Patch document. */ public JsonPatchDocument() { this(null); } /** * Creates a new JSON Patch document. * <p> * If {@code serializer} isn't specified {@link JacksonAdapter} will be used. * * @param serializer The {@link JsonSerializer} that will be used to serialize patch operation values. */ public JsonPatchDocument(JsonSerializer serializer) { this.operations = new ArrayList<>(); this.serializer = serializer; } List<JsonPatchOperation> getOperations() { return new ArrayList<>(operations); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAdd * * @param path The path to apply the addition. * @param value The value that will be serialized and added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAdd(String path, Object value) { return appendAddInternal(path, serializeValue(value)); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAddRaw * * @param path The path to apply the addition. * @param rawJson The raw JSON value that will be added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAddRaw(String path, String rawJson) { return appendAddInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendAddInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.ADD, null, path, rawJsonOption); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplace * * @param path The path to replace. * @param value The value will be serialized and used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplace(String path, Object value) { return appendReplaceInternal(path, serializeValue(value)); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplaceRaw * * @param path The path to replace. * @param rawJson The raw JSON value that will be used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplaceRaw(String path, String rawJson) { return appendReplaceInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendReplaceInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REPLACE, null, path, rawJsonOption); } /** * Appends a "copy" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendCopy * * @param from The path to copy from. * @param path The path to copy to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendCopy(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.COPY, from, path, Option.uninitialized()); } /** * Appends a "move" operation to this JSON Patch document. * <p> * For the operation to be successful {@code path} cannot be a child node of {@code from}. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendMove * * @param from The path to move from. * @param path The path to move to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendMove(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.MOVE, from, path, Option.uninitialized()); } /** * Appends a "remove" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendRemove * * @param path The path to remove. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendRemove(String path) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REMOVE, null, path, Option.uninitialized()); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTest * * @param path The path to test. * @param value The value that will be serialized and used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTest(String path, Object value) { return appendTestInternal(path, serializeValue(value)); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTestRaw * * @param path The path to test. * @param rawJson The raw JSON value that will be used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTestRaw(String path, String rawJson) { return appendTestInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendTestInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.TEST, null, path, rawJsonOption); } private JsonPatchDocument appendOperation(JsonPatchOperationKind operationKind, String from, String path, Option<String> optionalValue) { operations.add(new JsonPatchOperation(operationKind, from, path, optionalValue)); return this; } /** * Gets a formatted JSON string representation of this JSON Patch document. * * @return The formatted JSON String representing this JSON Patch docuemnt. */ @Override public String toString() { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < operations.size(); i++) { if (i > 0) { builder.append(","); } operations.get(i).buildString(builder); } return builder.append("]").toString(); } }
Made the static violatile.
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (DEFAULT_SERIALIZER == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (DEFAULT_SERIALIZER == null) { DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(); } } } DEFAULT_SERIALIZER.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
if (DEFAULT_SERIALIZER == null) {
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (defaultSerializer == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (defaultSerializer == null) { defaultSerializer = JsonSerializerProviders.createInstance(); } } } defaultSerializer.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
class JsonPatchDocument { private static final Object SERIALIZER_INSTANTIATION_SYNCHRONIZER = new Object(); private static JsonSerializer DEFAULT_SERIALIZER; @JsonIgnore private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class); @JsonValue private final List<JsonPatchOperation> operations; @JsonIgnore private final JsonSerializer serializer; /** * Creates a new JSON Patch document. */ public JsonPatchDocument() { this(null); } /** * Creates a new JSON Patch document. * <p> * If {@code serializer} isn't specified {@link JacksonAdapter} will be used. * * @param serializer The {@link JsonSerializer} that will be used to serialize patch operation values. */ public JsonPatchDocument(JsonSerializer serializer) { this.operations = new ArrayList<>(); this.serializer = serializer; } List<JsonPatchOperation> getOperations() { return new ArrayList<>(operations); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAdd * * @param path The path to apply the addition. * @param value The value that will be serialized and added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAdd(String path, Object value) { return appendAddInternal(path, () -> serializeValue(value)); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAddRaw * * @param path The path to apply the addition. * @param rawJson The raw JSON value that will be added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAddRaw(String path, String rawJson) { return appendAddInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendAddInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.ADD, null, path, jsonSupplier.get()); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplace * * @param path The path to replace. * @param value The value will be serialized and used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplace(String path, Object value) { return appendReplaceInternal(path, () -> serializeValue(value)); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplaceRaw * * @param path The path to replace. * @param rawJson The raw JSON value that will be used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplaceRaw(String path, String rawJson) { return appendReplaceInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendReplaceInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REPLACE, null, path, jsonSupplier.get()); } /** * Appends a "copy" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendCopy * * @param from The path to copy from. * @param path The path to copy to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendCopy(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.COPY, from, path, Option.uninitialized()); } /** * Appends a "move" operation to this JSON Patch document. * <p> * For the operation to be successful {@code path} cannot be a child node of {@code from}. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendMove * * @param from The path to move from. * @param path The path to move to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendMove(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.MOVE, from, path, Option.uninitialized()); } /** * Appends a "remove" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendRemove * * @param path The path to remove. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendRemove(String path) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REMOVE, null, path, Option.uninitialized()); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTest * * @param path The path to test. * @param value The value that will be serialized and used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTest(String path, Object value) { return appendTestInternal(path, () -> serializeValue(value)); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTestRaw * * @param path The path to test. * @param rawJson The raw JSON value that will be used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTestRaw(String path, String rawJson) { return appendTestInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendTestInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.TEST, null, path, jsonSupplier.get()); } private JsonPatchDocument appendOperation(JsonPatchOperationKind operationKind, String from, String path, Option<String> optionalValue) { operations.add(new JsonPatchOperation(operationKind, from, path, optionalValue)); return this; } /** * Gets a formatted JSON string representation of this JSON Patch document. * * @return The formatted JSON String representing this JSON Patch docuemnt. */ @Override public String toString() { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < operations.size(); i++) { if (i > 0) { builder.append(","); } operations.get(i).buildString(builder); } return builder.append("]").toString(); } }
class JsonPatchDocument { private static final Object SERIALIZER_INSTANTIATION_SYNCHRONIZER = new Object(); private static volatile JsonSerializer defaultSerializer; @JsonIgnore private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class); @JsonValue private final List<JsonPatchOperation> operations; @JsonIgnore private final JsonSerializer serializer; /** * Creates a new JSON Patch document. */ public JsonPatchDocument() { this(null); } /** * Creates a new JSON Patch document. * <p> * If {@code serializer} isn't specified {@link JacksonAdapter} will be used. * * @param serializer The {@link JsonSerializer} that will be used to serialize patch operation values. */ public JsonPatchDocument(JsonSerializer serializer) { this.operations = new ArrayList<>(); this.serializer = serializer; } List<JsonPatchOperation> getOperations() { return new ArrayList<>(operations); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAdd * * @param path The path to apply the addition. * @param value The value that will be serialized and added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAdd(String path, Object value) { return appendAddInternal(path, serializeValue(value)); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAddRaw * * @param path The path to apply the addition. * @param rawJson The raw JSON value that will be added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAddRaw(String path, String rawJson) { return appendAddInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendAddInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.ADD, null, path, rawJsonOption); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplace * * @param path The path to replace. * @param value The value will be serialized and used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplace(String path, Object value) { return appendReplaceInternal(path, serializeValue(value)); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplaceRaw * * @param path The path to replace. * @param rawJson The raw JSON value that will be used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplaceRaw(String path, String rawJson) { return appendReplaceInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendReplaceInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REPLACE, null, path, rawJsonOption); } /** * Appends a "copy" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendCopy * * @param from The path to copy from. * @param path The path to copy to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendCopy(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.COPY, from, path, Option.uninitialized()); } /** * Appends a "move" operation to this JSON Patch document. * <p> * For the operation to be successful {@code path} cannot be a child node of {@code from}. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendMove * * @param from The path to move from. * @param path The path to move to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendMove(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.MOVE, from, path, Option.uninitialized()); } /** * Appends a "remove" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendRemove * * @param path The path to remove. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendRemove(String path) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REMOVE, null, path, Option.uninitialized()); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTest * * @param path The path to test. * @param value The value that will be serialized and used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTest(String path, Object value) { return appendTestInternal(path, serializeValue(value)); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTestRaw * * @param path The path to test. * @param rawJson The raw JSON value that will be used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTestRaw(String path, String rawJson) { return appendTestInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendTestInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.TEST, null, path, rawJsonOption); } private JsonPatchDocument appendOperation(JsonPatchOperationKind operationKind, String from, String path, Option<String> optionalValue) { operations.add(new JsonPatchOperation(operationKind, from, path, optionalValue)); return this; } /** * Gets a formatted JSON string representation of this JSON Patch document. * * @return The formatted JSON String representing this JSON Patch docuemnt. */ @Override public String toString() { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < operations.size(); i++) { if (i > 0) { builder.append(","); } operations.get(i).buildString(builder); } return builder.append("]").toString(); } }
with volatile, happens-before is guaranteed, so DCL should be good now.
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (DEFAULT_SERIALIZER == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (DEFAULT_SERIALIZER == null) { DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(); } } } DEFAULT_SERIALIZER.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
if (DEFAULT_SERIALIZER == null) {
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (defaultSerializer == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (defaultSerializer == null) { defaultSerializer = JsonSerializerProviders.createInstance(); } } } defaultSerializer.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
class JsonPatchDocument { private static final Object SERIALIZER_INSTANTIATION_SYNCHRONIZER = new Object(); private static JsonSerializer DEFAULT_SERIALIZER; @JsonIgnore private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class); @JsonValue private final List<JsonPatchOperation> operations; @JsonIgnore private final JsonSerializer serializer; /** * Creates a new JSON Patch document. */ public JsonPatchDocument() { this(null); } /** * Creates a new JSON Patch document. * <p> * If {@code serializer} isn't specified {@link JacksonAdapter} will be used. * * @param serializer The {@link JsonSerializer} that will be used to serialize patch operation values. */ public JsonPatchDocument(JsonSerializer serializer) { this.operations = new ArrayList<>(); this.serializer = serializer; } List<JsonPatchOperation> getOperations() { return new ArrayList<>(operations); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAdd * * @param path The path to apply the addition. * @param value The value that will be serialized and added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAdd(String path, Object value) { return appendAddInternal(path, () -> serializeValue(value)); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAddRaw * * @param path The path to apply the addition. * @param rawJson The raw JSON value that will be added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAddRaw(String path, String rawJson) { return appendAddInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendAddInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.ADD, null, path, jsonSupplier.get()); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplace * * @param path The path to replace. * @param value The value will be serialized and used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplace(String path, Object value) { return appendReplaceInternal(path, () -> serializeValue(value)); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplaceRaw * * @param path The path to replace. * @param rawJson The raw JSON value that will be used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplaceRaw(String path, String rawJson) { return appendReplaceInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendReplaceInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REPLACE, null, path, jsonSupplier.get()); } /** * Appends a "copy" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendCopy * * @param from The path to copy from. * @param path The path to copy to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendCopy(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.COPY, from, path, Option.uninitialized()); } /** * Appends a "move" operation to this JSON Patch document. * <p> * For the operation to be successful {@code path} cannot be a child node of {@code from}. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendMove * * @param from The path to move from. * @param path The path to move to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendMove(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.MOVE, from, path, Option.uninitialized()); } /** * Appends a "remove" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendRemove * * @param path The path to remove. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendRemove(String path) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REMOVE, null, path, Option.uninitialized()); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTest * * @param path The path to test. * @param value The value that will be serialized and used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTest(String path, Object value) { return appendTestInternal(path, () -> serializeValue(value)); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTestRaw * * @param path The path to test. * @param rawJson The raw JSON value that will be used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTestRaw(String path, String rawJson) { return appendTestInternal(path, () -> Option.of(rawJson)); } private JsonPatchDocument appendTestInternal(String path, Supplier<Option<String>> jsonSupplier) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.TEST, null, path, jsonSupplier.get()); } private JsonPatchDocument appendOperation(JsonPatchOperationKind operationKind, String from, String path, Option<String> optionalValue) { operations.add(new JsonPatchOperation(operationKind, from, path, optionalValue)); return this; } /** * Gets a formatted JSON string representation of this JSON Patch document. * * @return The formatted JSON String representing this JSON Patch docuemnt. */ @Override public String toString() { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < operations.size(); i++) { if (i > 0) { builder.append(","); } operations.get(i).buildString(builder); } return builder.append("]").toString(); } }
class JsonPatchDocument { private static final Object SERIALIZER_INSTANTIATION_SYNCHRONIZER = new Object(); private static volatile JsonSerializer defaultSerializer; @JsonIgnore private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class); @JsonValue private final List<JsonPatchOperation> operations; @JsonIgnore private final JsonSerializer serializer; /** * Creates a new JSON Patch document. */ public JsonPatchDocument() { this(null); } /** * Creates a new JSON Patch document. * <p> * If {@code serializer} isn't specified {@link JacksonAdapter} will be used. * * @param serializer The {@link JsonSerializer} that will be used to serialize patch operation values. */ public JsonPatchDocument(JsonSerializer serializer) { this.operations = new ArrayList<>(); this.serializer = serializer; } List<JsonPatchOperation> getOperations() { return new ArrayList<>(operations); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAdd * * @param path The path to apply the addition. * @param value The value that will be serialized and added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAdd(String path, Object value) { return appendAddInternal(path, serializeValue(value)); } /** * Appends an "add" operation to this JSON Patch document. * <p> * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendAddRaw * * @param path The path to apply the addition. * @param rawJson The raw JSON value that will be added to the path. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendAddRaw(String path, String rawJson) { return appendAddInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendAddInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.ADD, null, path, rawJsonOption); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplace * * @param path The path to replace. * @param value The value will be serialized and used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplace(String path, Object value) { return appendReplaceInternal(path, serializeValue(value)); } /** * Appends a "replace" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendReplaceRaw * * @param path The path to replace. * @param rawJson The raw JSON value that will be used as the replacement. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendReplaceRaw(String path, String rawJson) { return appendReplaceInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendReplaceInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REPLACE, null, path, rawJsonOption); } /** * Appends a "copy" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendCopy * * @param from The path to copy from. * @param path The path to copy to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendCopy(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.COPY, from, path, Option.uninitialized()); } /** * Appends a "move" operation to this JSON Patch document. * <p> * For the operation to be successful {@code path} cannot be a child node of {@code from}. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendMove * * @param from The path to move from. * @param path The path to move to. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code from} or {@code path} is null. */ public JsonPatchDocument appendMove(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.MOVE, from, path, Option.uninitialized()); } /** * Appends a "remove" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendRemove * * @param path The path to remove. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendRemove(String path) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.REMOVE, null, path, Option.uninitialized()); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTest * * @param path The path to test. * @param value The value that will be serialized and used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTest(String path, Object value) { return appendTestInternal(path, serializeValue(value)); } /** * Appends a "test" operation to this JSON Patch document. * <p> * See <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.core.util.jsonpatch.JsonPatchDocument.appendTestRaw * * @param path The path to test. * @param rawJson The raw JSON value that will be used to test against. * @return The updated JsonPatchDocument object. * @throws NullPointerException If {@code path} is null. */ public JsonPatchDocument appendTestRaw(String path, String rawJson) { return appendTestInternal(path, Option.of(rawJson)); } private JsonPatchDocument appendTestInternal(String path, Option<String> rawJsonOption) { Objects.requireNonNull(path, "'path' cannot be null."); return appendOperation(JsonPatchOperationKind.TEST, null, path, rawJsonOption); } private JsonPatchDocument appendOperation(JsonPatchOperationKind operationKind, String from, String path, Option<String> optionalValue) { operations.add(new JsonPatchOperation(operationKind, from, path, optionalValue)); return this; } /** * Gets a formatted JSON string representation of this JSON Patch document. * * @return The formatted JSON String representing this JSON Patch docuemnt. */ @Override public String toString() { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < operations.size(); i++) { if (i > 0) { builder.append(","); } operations.get(i).buildString(builder); } return builder.append("]").toString(); } }
still need to remove this block. It's what I was asking Srikanta about during the tutorial. Let me find his answer about how to do it
public void canGetExistingChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.getChatThread(chatThreadClient.getChatThreadId())) .assertNext(chatThread -> { assertEquals(chatThreadClient.getChatThreadId(), chatThread.getId()); }) .verifyComplete(); }
ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block();
public void canGetExistingChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.getChatThread(chatThreadClient.getChatThreadId()); })) .assertNext(chatThread -> { assertEquals(chatThreadClientRef.get().getChatThreadId(), chatThread.getId()); }) .verifyComplete(); }
class ChatAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); assertNotNull(communicationClient); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canCreateThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThread(threadRequest)) .assertNext(chatThreadClient -> { assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canCreateThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThreadWithResponse(threadRequest)) .assertNext(chatThreadClientResponse -> { ChatThreadAsyncClient chatThreadClient = chatThreadClientResponse.getValue(); assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canGetChatThreadClient() { String threadId = "19:fe0a2f65a7834185b29164a7de57699c@thread.v2"; ChatThreadAsyncClient chatThreadClient = client.getChatThreadClient(threadId); assertNotNull(chatThreadClient); assertEquals(chatThreadClient.getChatThreadId(), threadId); } @Test @Test public void canGetExistingChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.getChatThreadWithResponse(chatThreadClient.getChatThreadId())) .assertNext(chatThreadResponse -> { ChatThread chatThread = chatThreadResponse.getValue(); assertEquals(chatThreadClient.getChatThreadId(), chatThread.getId()); }) .verifyComplete(); } @Test public void getNotFoundOnNonExistingChatThread() { StepVerifier.create(client.getChatThread("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void getNotFoundOnNonExistingChatThreadWithResponse() { StepVerifier.create(client.getChatThreadWithResponse("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void canDeleteChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.deleteChatThread(chatThreadClient.getChatThreadId())) .verifyComplete(); } @Test public void canDeleteChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.deleteChatThreadWithResponse(chatThreadClient.getChatThreadId())) .assertNext(response -> { assertEquals(response.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canListChatThreads() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); client.createChatThread(threadRequest).block(); client.createChatThread(threadRequest).block(); Thread.sleep(500); PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads()); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); } @Test public void canListChatThreadsWithMaxPageSize() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); client.createChatThread(threadRequest).block(); client.createChatThread(threadRequest).block(); Thread.sleep(500); ListChatThreadsOptions options = new ListChatThreadsOptions(); options.setMaxPageSize(10); PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads(options)); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); } }
class ChatAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); assertNotNull(communicationClient); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canCreateThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThread(threadRequest)) .assertNext(chatThreadClient -> { assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canCreateThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThreadWithResponse(threadRequest)) .assertNext(chatThreadClientResponse -> { ChatThreadAsyncClient chatThreadClient = chatThreadClientResponse.getValue(); assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canGetChatThreadClient() { String threadId = "19:fe0a2f65a7834185b29164a7de57699c@thread.v2"; ChatThreadAsyncClient chatThreadClient = client.getChatThreadClient(threadId); assertNotNull(chatThreadClient); assertEquals(chatThreadClient.getChatThreadId(), threadId); } @Test @Test public void canGetExistingChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.getChatThreadWithResponse(chatThreadClient.getChatThreadId()); })) .assertNext(chatThreadResponse -> { ChatThread chatThread = chatThreadResponse.getValue(); assertEquals(chatThreadClientRef.get().getChatThreadId(), chatThread.getId()); }) .verifyComplete(); } @Test public void getNotFoundOnNonExistingChatThread() { StepVerifier.create(client.getChatThread("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void getNotFoundOnNonExistingChatThreadWithResponse() { StepVerifier.create(client.getChatThreadWithResponse("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void canDeleteChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.deleteChatThread(chatThreadClient.getChatThreadId()); }) ) .verifyComplete(); } @Test public void canDeleteChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.deleteChatThreadWithResponse(chatThreadClient.getChatThreadId()); }) ) .assertNext(deleteResponse -> { assertEquals(deleteResponse.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canListChatThreads() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create( client.createChatThread(threadRequest) .concatWith(client.createChatThread(threadRequest))) .assertNext(chatThreadClient -> { PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads()); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); }); } @Test public void canListChatThreadsWithMaxPageSize() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ListChatThreadsOptions options = new ListChatThreadsOptions(); options.setMaxPageSize(10); StepVerifier.create( client.createChatThread(threadRequest) .concatWith(client.createChatThread(threadRequest))) .assertNext(chatThreadClient -> { PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads(options)); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); }); } }
Same comment here, need to get rid of this .block() too
public void canDeleteExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.deleteMessage(response.getId())) .verifyComplete(); }
SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block();
public void canDeleteExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { return chatThreadClient.deleteMessage(response.getId()); }) ) .verifyComplete(); }
class ChatThreadAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatThreadAsyncClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private ChatThreadAsyncClient chatThreadClient; private String threadId; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; private CommunicationUser firstAddedThreadMember; private CommunicationUser secondAddedThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions(firstThreadMember.getId(), secondThreadMember.getId()); chatThreadClient = client.createChatThread(threadRequest).block(); threadId = chatThreadClient.getChatThreadId(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canUpdateThread() { UpdateChatThreadOptions threadRequest = ChatOptionsProvider.updateThreadOptions(); StepVerifier.create(chatThreadClient.updateChatThread(threadRequest)) .assertNext(noResp -> { StepVerifier.create(client.getChatThread(threadId)).assertNext(chatThread -> { assertEquals(chatThread.getTopic(), threadRequest.getTopic()); }) .verifyComplete(); }); } @Test public void canUpdateThreadWithResponse() { UpdateChatThreadOptions threadRequest = ChatOptionsProvider.updateThreadOptions(); StepVerifier.create(chatThreadClient.updateChatThreadWithResponse(threadRequest)) .assertNext(updateThreadResponse -> { assertEquals(updateThreadResponse.getStatusCode(), 200); StepVerifier.create(client.getChatThread(threadId)).assertNext(chatThread -> { assertEquals(chatThread.getTopic(), threadRequest.getTopic()); }) .verifyComplete(); }) .verifyComplete(); } @Test public void canAddListAndRemoveMembersAsync() throws InterruptedException { firstAddedThreadMember = communicationClient.createUser(); secondAddedThreadMember = communicationClient.createUser(); AddChatThreadMembersOptions options = ChatOptionsProvider.addThreadMembersOptions( firstAddedThreadMember.getId(), secondAddedThreadMember.getId()); StepVerifier.create(chatThreadClient.addMembers(options)) .assertNext(noResp -> { PagedIterable<ChatThreadMember> membersResponse = new PagedIterable<>(chatThreadClient.listMembers()); List<ChatThreadMember> returnedMembers = new ArrayList<ChatThreadMember>(); membersResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedMembers.add(item)); }); for (ChatThreadMember member: options.getMembers()) { assertTrue(checkMembersListContainsMemberId(returnedMembers, member.getUser().getId())); } assertTrue(returnedMembers.size() == 4); }); for (ChatThreadMember member: options.getMembers()) { StepVerifier.create(chatThreadClient.removeMember(member.getUser())) .verifyComplete(); } } @Test public void canAddListAndRemoveMembersWithResponseAsync() throws InterruptedException { firstAddedThreadMember = communicationClient.createUser(); secondAddedThreadMember = communicationClient.createUser(); AddChatThreadMembersOptions options = ChatOptionsProvider.addThreadMembersOptions( firstAddedThreadMember.getId(), secondAddedThreadMember.getId()); StepVerifier.create(chatThreadClient.addMembersWithResponse(options)) .assertNext(addMembersResponse -> { assertEquals(addMembersResponse.getStatusCode(), 207); PagedIterable<ChatThreadMember> membersResponse = new PagedIterable<>(chatThreadClient.listMembers()); List<ChatThreadMember> returnedMembers = new ArrayList<ChatThreadMember>(); membersResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedMembers.add(item)); }); for (ChatThreadMember member: options.getMembers()) { assertTrue(checkMembersListContainsMemberId(returnedMembers, member.getUser().getId())); } assertTrue(returnedMembers.size() == 4); for (ChatThreadMember member: options.getMembers()) { StepVerifier.create(chatThreadClient.removeMemberWithResponse(member.getUser())) .assertNext(resp -> { assertEquals(resp.getStatusCode(), 204); }) .verifyComplete(); } }) .verifyComplete(); } @Test public void canSendThenGetMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create(chatThreadClient.sendMessage(messageRequest)) .assertNext(response -> { StepVerifier.create(chatThreadClient.getMessage(response.getId())) .assertNext(message -> { assertEquals(message.getContent(), messageRequest.getContent()); assertEquals(message.getPriority(), messageRequest.getPriority()); assertEquals(message.getSenderDisplayName(), messageRequest.getSenderDisplayName()); }) .verifyComplete(); }) .verifyComplete(); } @Test public void canSendThenGetMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create(chatThreadClient.sendMessageWithResponse(messageRequest)) .assertNext(sendResponse -> { StepVerifier.create(chatThreadClient.getMessageWithResponse(sendResponse.getValue().getId())) .assertNext(getResponse -> { ChatMessage message = getResponse.getValue(); assertEquals(message.getContent(), messageRequest.getContent()); assertEquals(message.getPriority(), messageRequest.getPriority()); assertEquals(message.getSenderDisplayName(), messageRequest.getSenderDisplayName()); }) .verifyComplete(); }) .verifyComplete(); } @Test @Test public void canDeleteExistingMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.deleteMessageWithResponse(response.getId())) .assertNext(deleteResponse -> { assertEquals(deleteResponse.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canUpdateExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); UpdateChatMessageOptions updateMessageRequest = ChatOptionsProvider.updateMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.updateMessage(response.getId(), updateMessageRequest)) .assertNext(noResp -> { StepVerifier.create(chatThreadClient.getMessage(response.getId())) .assertNext(message -> { assertEquals(message.getContent(), updateMessageRequest.getContent()); }) .verifyComplete(); }); } @Test public void canUpdateExistingMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); UpdateChatMessageOptions updateMessageRequest = ChatOptionsProvider.updateMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.updateMessageWithResponse(response.getId(), updateMessageRequest)) .assertNext(updateResponse -> { assertEquals(updateResponse.getStatusCode(), 200); StepVerifier.create(chatThreadClient.getMessage(response.getId())) .assertNext(message -> { assertEquals(message.getContent(), updateMessageRequest.getContent()); }) .verifyComplete(); }) .verifyComplete(); } @Test public void canListMessages() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); chatThreadClient.sendMessage(messageRequest).block(); chatThreadClient.sendMessage(messageRequest).block(); PagedIterable<ChatMessage> messagesResponse = new PagedIterable<ChatMessage>(chatThreadClient.listMessages()); List<ChatMessage> returnedMessages = new ArrayList<ChatMessage>(); messagesResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> { if (item.getType().equals("Text")) { returnedMessages.add(item); } }); }); assertTrue(returnedMessages.size() == 2); } @Test public void canListMessagesWithOptions() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); chatThreadClient.sendMessage(messageRequest).block(); chatThreadClient.sendMessage(messageRequest).block(); ListChatMessagesOptions options = new ListChatMessagesOptions(); options.setMaxPageSize(10); options.setStartTime(OffsetDateTime.parse("2020-09-08T01:02:14.387Z")); PagedIterable<ChatMessage> messagesResponse = new PagedIterable<ChatMessage>(chatThreadClient.listMessages(options)); List<ChatMessage> returnedMessages = new ArrayList<ChatMessage>(); messagesResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> { if (item.getType().equals("Text")) { returnedMessages.add(item); } }); }); assertTrue(returnedMessages.size() == 2); } @Test public void canSendTypingNotification() { StepVerifier.create(chatThreadClient.sendTypingNotification()) .verifyComplete(); } @Test public void canSendTypingNotificationWithResponse() { StepVerifier.create(chatThreadClient.sendTypingNotificationWithResponse()) .assertNext(response -> { assertEquals(response.getStatusCode(), 200); }) .verifyComplete(); } @Test public void canSendThenListReadReceipts() throws InterruptedException { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.sendReadReceipt(response.getId())) .assertNext(noResp -> { PagedIterable<ReadReceipt> readReceiptsResponse = new PagedIterable<ReadReceipt>(chatThreadClient.listReadReceipts()); List<ReadReceipt> returnedReadReceipts = new ArrayList<ReadReceipt>(); readReceiptsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedReadReceipts.add(item)); }); if (interceptorManager.isPlaybackMode()) { assertTrue(returnedReadReceipts.size() > 0); checkReadReceiptListContainsMessageId(returnedReadReceipts, response.getId()); } }); } @Test public void canSendThenListReadReceiptsWithResponse() throws InterruptedException { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.sendReadReceiptWithResponse(response.getId())) .assertNext(receiptResponse -> { assertEquals(receiptResponse.getStatusCode(), 201); PagedIterable<ReadReceipt> readReceiptsResponse = new PagedIterable<ReadReceipt>(chatThreadClient.listReadReceipts()); List<ReadReceipt> returnedReadReceipts = new ArrayList<ReadReceipt>(); readReceiptsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedReadReceipts.add(item)); }); if (interceptorManager.isPlaybackMode()) { assertTrue(returnedReadReceipts.size() > 0); checkReadReceiptListContainsMessageId(returnedReadReceipts, response.getId()); } }) .verifyComplete(); } }
class ChatThreadAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatThreadAsyncClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private ChatThreadAsyncClient chatThreadClient; private String threadId; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; private CommunicationUser firstAddedThreadMember; private CommunicationUser secondAddedThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions(firstThreadMember.getId(), secondThreadMember.getId()); chatThreadClient = client.createChatThread(threadRequest).block(); threadId = chatThreadClient.getChatThreadId(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canUpdateThread() { UpdateChatThreadOptions threadRequest = ChatOptionsProvider.updateThreadOptions(); StepVerifier.create( chatThreadClient.updateChatThread(threadRequest) .flatMap(noResp -> { return client.getChatThread(threadId); }) ) .assertNext(chatThread -> { assertEquals(chatThread.getTopic(), threadRequest.getTopic()); }); } @Test public void canUpdateThreadWithResponse() { UpdateChatThreadOptions threadRequest = ChatOptionsProvider.updateThreadOptions(); StepVerifier.create( chatThreadClient.updateChatThreadWithResponse(threadRequest) .flatMap(updateThreadResponse -> { assertEquals(updateThreadResponse.getStatusCode(), 200); return client.getChatThread(threadId); }) ) .assertNext(chatThread -> { assertEquals(chatThread.getTopic(), threadRequest.getTopic()); }) .verifyComplete(); } @Test public void canAddListAndRemoveMembersAsync() throws InterruptedException { firstAddedThreadMember = communicationClient.createUser(); secondAddedThreadMember = communicationClient.createUser(); AddChatThreadMembersOptions options = ChatOptionsProvider.addThreadMembersOptions( firstAddedThreadMember.getId(), secondAddedThreadMember.getId()); StepVerifier.create(chatThreadClient.addMembers(options)) .assertNext(noResp -> { PagedIterable<ChatThreadMember> membersResponse = new PagedIterable<>(chatThreadClient.listMembers()); List<ChatThreadMember> returnedMembers = new ArrayList<ChatThreadMember>(); membersResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedMembers.add(item)); }); for (ChatThreadMember member: options.getMembers()) { assertTrue(checkMembersListContainsMemberId(returnedMembers, member.getUser().getId())); } assertTrue(returnedMembers.size() == 4); }); for (ChatThreadMember member: options.getMembers()) { StepVerifier.create(chatThreadClient.removeMember(member.getUser())) .verifyComplete(); } } @Test public void canAddListAndRemoveMembersWithResponseAsync() throws InterruptedException { firstAddedThreadMember = communicationClient.createUser(); secondAddedThreadMember = communicationClient.createUser(); AddChatThreadMembersOptions options = ChatOptionsProvider.addThreadMembersOptions( firstAddedThreadMember.getId(), secondAddedThreadMember.getId()); StepVerifier.create(chatThreadClient.addMembersWithResponse(options)) .assertNext(addMembersResponse -> { assertEquals(addMembersResponse.getStatusCode(), 207); PagedIterable<ChatThreadMember> membersResponse = new PagedIterable<>(chatThreadClient.listMembers()); List<ChatThreadMember> returnedMembers = new ArrayList<ChatThreadMember>(); membersResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedMembers.add(item)); }); for (ChatThreadMember member: options.getMembers()) { assertTrue(checkMembersListContainsMemberId(returnedMembers, member.getUser().getId())); } assertTrue(returnedMembers.size() == 4); }) .verifyComplete(); for (ChatThreadMember member: options.getMembers()) { StepVerifier.create(chatThreadClient.removeMemberWithResponse(member.getUser())) .assertNext(resp -> { assertEquals(resp.getStatusCode(), 204); }) .verifyComplete(); } } @Test public void canSendThenGetMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier .create(chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { return chatThreadClient.getMessage(response.getId()); }) ) .assertNext(message -> { assertEquals(message.getContent(), messageRequest.getContent()); assertEquals(message.getPriority(), messageRequest.getPriority()); assertEquals(message.getSenderDisplayName(), messageRequest.getSenderDisplayName()); }) .verifyComplete(); } @Test public void canSendThenGetMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier .create(chatThreadClient.sendMessageWithResponse(messageRequest) .flatMap(sendResponse -> { assertEquals(sendResponse.getStatusCode(), 201); return chatThreadClient.getMessageWithResponse(sendResponse.getValue().getId()); }) ) .assertNext(getResponse -> { ChatMessage message = getResponse.getValue(); assertEquals(message.getContent(), messageRequest.getContent()); assertEquals(message.getPriority(), messageRequest.getPriority()); assertEquals(message.getSenderDisplayName(), messageRequest.getSenderDisplayName()); }) .verifyComplete(); } @Test @Test public void canDeleteExistingMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { return chatThreadClient.deleteMessageWithResponse(response.getId()); }) ) .assertNext(deleteResponse -> { assertEquals(deleteResponse.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canUpdateExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); UpdateChatMessageOptions updateMessageRequest = ChatOptionsProvider.updateMessageOptions(); AtomicReference<SendChatMessageResult> messageResponseRef = new AtomicReference<>(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { messageResponseRef.set(response); return chatThreadClient.updateMessage(response.getId(), updateMessageRequest); }) .flatMap((Void resp) -> { return chatThreadClient.getMessage(messageResponseRef.get().getId()); }) ) .assertNext(message -> { assertEquals(message.getContent(), updateMessageRequest.getContent()); }); } @Test public void canUpdateExistingMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); UpdateChatMessageOptions updateMessageRequest = ChatOptionsProvider.updateMessageOptions(); AtomicReference<SendChatMessageResult> messageResponseRef = new AtomicReference<>(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap((SendChatMessageResult response) -> { messageResponseRef.set(response); return chatThreadClient.updateMessageWithResponse(response.getId(), updateMessageRequest); }) .flatMap((Response<Void> updateResponse) -> { assertEquals(updateResponse.getStatusCode(), 200); return chatThreadClient.getMessage(messageResponseRef.get().getId()); }) ) .assertNext(message -> { assertEquals(message.getContent(), updateMessageRequest.getContent()); }) .verifyComplete(); } @Test public void canListMessages() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .concatWith(chatThreadClient.sendMessage(messageRequest)) ) .assertNext((message) -> { PagedIterable<ChatMessage> messagesResponse = new PagedIterable<ChatMessage>(chatThreadClient.listMessages()); List<ChatMessage> returnedMessages = new ArrayList<ChatMessage>(); messagesResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> { if (item.getType().equals("Text")) { returnedMessages.add(item); } }); }); assertTrue(returnedMessages.size() == 2); }); } @Test public void canListMessagesWithOptions() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); ListChatMessagesOptions options = new ListChatMessagesOptions(); options.setMaxPageSize(10); options.setStartTime(OffsetDateTime.parse("2020-09-08T01:02:14.387Z")); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .concatWith(chatThreadClient.sendMessage(messageRequest))) .assertNext((message) -> { PagedIterable<ChatMessage> messagesResponse = new PagedIterable<ChatMessage>(chatThreadClient.listMessages(options)); List<ChatMessage> returnedMessages = new ArrayList<ChatMessage>(); messagesResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> { if (item.getType().equals("Text")) { returnedMessages.add(item); } }); }); assertTrue(returnedMessages.size() == 2); }); } @Test public void canSendTypingNotification() { StepVerifier.create(chatThreadClient.sendTypingNotification()) .verifyComplete(); } @Test public void canSendTypingNotificationWithResponse() { StepVerifier.create(chatThreadClient.sendTypingNotificationWithResponse()) .assertNext(response -> { assertEquals(response.getStatusCode(), 200); }) .verifyComplete(); } @Test public void canSendThenListReadReceipts() throws InterruptedException { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); AtomicReference<SendChatMessageResult> messageResponseRef = new AtomicReference<>(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { messageResponseRef.set(response); return chatThreadClient.sendReadReceipt(response.getId()); }) ) .assertNext(noResp -> { PagedIterable<ReadReceipt> readReceiptsResponse = new PagedIterable<ReadReceipt>(chatThreadClient.listReadReceipts()); List<ReadReceipt> returnedReadReceipts = new ArrayList<ReadReceipt>(); readReceiptsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedReadReceipts.add(item)); }); if (interceptorManager.isPlaybackMode()) { assertTrue(returnedReadReceipts.size() > 0); checkReadReceiptListContainsMessageId(returnedReadReceipts, messageResponseRef.get().getId()); } }); } @Test public void canSendThenListReadReceiptsWithResponse() throws InterruptedException { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); AtomicReference<SendChatMessageResult> messageResponseRef = new AtomicReference<>(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { messageResponseRef.set(response); return chatThreadClient.sendReadReceiptWithResponse(response.getId()); }) ) .assertNext(receiptResponse -> { assertEquals(receiptResponse.getStatusCode(), 201); PagedIterable<ReadReceipt> readReceiptsResponse = new PagedIterable<ReadReceipt>(chatThreadClient.listReadReceipts()); List<ReadReceipt> returnedReadReceipts = new ArrayList<ReadReceipt>(); readReceiptsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedReadReceipts.add(item)); }); if (interceptorManager.isPlaybackMode()) { assertTrue(returnedReadReceipts.size() > 0); checkReadReceiptListContainsMessageId(returnedReadReceipts, messageResponseRef.get().getId()); } }) .verifyComplete(); } }
"What if we need to set up/create an object on the service first (as part of the arrange), before acting on it? Do we initialize the sync client too, and use it to arrange the setup? Or do we use a multi…" you can chain multiple service calls asynchronously through Reactor operators like then().. so, the first call will do the necessary setup on the service and then call the next method that you want to test
public void canGetExistingChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.getChatThread(chatThreadClient.getChatThreadId())) .assertNext(chatThread -> { assertEquals(chatThreadClient.getChatThreadId(), chatThread.getId()); }) .verifyComplete(); }
ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block();
public void canGetExistingChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.getChatThread(chatThreadClient.getChatThreadId()); })) .assertNext(chatThread -> { assertEquals(chatThreadClientRef.get().getChatThreadId(), chatThread.getId()); }) .verifyComplete(); }
class ChatAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); assertNotNull(communicationClient); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canCreateThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThread(threadRequest)) .assertNext(chatThreadClient -> { assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canCreateThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThreadWithResponse(threadRequest)) .assertNext(chatThreadClientResponse -> { ChatThreadAsyncClient chatThreadClient = chatThreadClientResponse.getValue(); assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canGetChatThreadClient() { String threadId = "19:fe0a2f65a7834185b29164a7de57699c@thread.v2"; ChatThreadAsyncClient chatThreadClient = client.getChatThreadClient(threadId); assertNotNull(chatThreadClient); assertEquals(chatThreadClient.getChatThreadId(), threadId); } @Test @Test public void canGetExistingChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.getChatThreadWithResponse(chatThreadClient.getChatThreadId())) .assertNext(chatThreadResponse -> { ChatThread chatThread = chatThreadResponse.getValue(); assertEquals(chatThreadClient.getChatThreadId(), chatThread.getId()); }) .verifyComplete(); } @Test public void getNotFoundOnNonExistingChatThread() { StepVerifier.create(client.getChatThread("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void getNotFoundOnNonExistingChatThreadWithResponse() { StepVerifier.create(client.getChatThreadWithResponse("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void canDeleteChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.deleteChatThread(chatThreadClient.getChatThreadId())) .verifyComplete(); } @Test public void canDeleteChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.deleteChatThreadWithResponse(chatThreadClient.getChatThreadId())) .assertNext(response -> { assertEquals(response.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canListChatThreads() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); client.createChatThread(threadRequest).block(); client.createChatThread(threadRequest).block(); Thread.sleep(500); PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads()); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); } @Test public void canListChatThreadsWithMaxPageSize() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); client.createChatThread(threadRequest).block(); client.createChatThread(threadRequest).block(); Thread.sleep(500); ListChatThreadsOptions options = new ListChatThreadsOptions(); options.setMaxPageSize(10); PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads(options)); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); } }
class ChatAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); assertNotNull(communicationClient); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canCreateThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThread(threadRequest)) .assertNext(chatThreadClient -> { assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canCreateThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThreadWithResponse(threadRequest)) .assertNext(chatThreadClientResponse -> { ChatThreadAsyncClient chatThreadClient = chatThreadClientResponse.getValue(); assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canGetChatThreadClient() { String threadId = "19:fe0a2f65a7834185b29164a7de57699c@thread.v2"; ChatThreadAsyncClient chatThreadClient = client.getChatThreadClient(threadId); assertNotNull(chatThreadClient); assertEquals(chatThreadClient.getChatThreadId(), threadId); } @Test @Test public void canGetExistingChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.getChatThreadWithResponse(chatThreadClient.getChatThreadId()); })) .assertNext(chatThreadResponse -> { ChatThread chatThread = chatThreadResponse.getValue(); assertEquals(chatThreadClientRef.get().getChatThreadId(), chatThread.getId()); }) .verifyComplete(); } @Test public void getNotFoundOnNonExistingChatThread() { StepVerifier.create(client.getChatThread("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void getNotFoundOnNonExistingChatThreadWithResponse() { StepVerifier.create(client.getChatThreadWithResponse("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void canDeleteChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.deleteChatThread(chatThreadClient.getChatThreadId()); }) ) .verifyComplete(); } @Test public void canDeleteChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.deleteChatThreadWithResponse(chatThreadClient.getChatThreadId()); }) ) .assertNext(deleteResponse -> { assertEquals(deleteResponse.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canListChatThreads() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create( client.createChatThread(threadRequest) .concatWith(client.createChatThread(threadRequest))) .assertNext(chatThreadClient -> { PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads()); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); }); } @Test public void canListChatThreadsWithMaxPageSize() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ListChatThreadsOptions options = new ListChatThreadsOptions(); options.setMaxPageSize(10); StepVerifier.create( client.createChatThread(threadRequest) .concatWith(client.createChatThread(threadRequest))) .assertNext(chatThreadClient -> { PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads(options)); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); }); } }
Done
public void canDeleteExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.deleteMessage(response.getId())) .verifyComplete(); }
SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block();
public void canDeleteExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { return chatThreadClient.deleteMessage(response.getId()); }) ) .verifyComplete(); }
class ChatThreadAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatThreadAsyncClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private ChatThreadAsyncClient chatThreadClient; private String threadId; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; private CommunicationUser firstAddedThreadMember; private CommunicationUser secondAddedThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions(firstThreadMember.getId(), secondThreadMember.getId()); chatThreadClient = client.createChatThread(threadRequest).block(); threadId = chatThreadClient.getChatThreadId(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canUpdateThread() { UpdateChatThreadOptions threadRequest = ChatOptionsProvider.updateThreadOptions(); StepVerifier.create(chatThreadClient.updateChatThread(threadRequest)) .assertNext(noResp -> { StepVerifier.create(client.getChatThread(threadId)).assertNext(chatThread -> { assertEquals(chatThread.getTopic(), threadRequest.getTopic()); }) .verifyComplete(); }); } @Test public void canUpdateThreadWithResponse() { UpdateChatThreadOptions threadRequest = ChatOptionsProvider.updateThreadOptions(); StepVerifier.create(chatThreadClient.updateChatThreadWithResponse(threadRequest)) .assertNext(updateThreadResponse -> { assertEquals(updateThreadResponse.getStatusCode(), 200); StepVerifier.create(client.getChatThread(threadId)).assertNext(chatThread -> { assertEquals(chatThread.getTopic(), threadRequest.getTopic()); }) .verifyComplete(); }) .verifyComplete(); } @Test public void canAddListAndRemoveMembersAsync() throws InterruptedException { firstAddedThreadMember = communicationClient.createUser(); secondAddedThreadMember = communicationClient.createUser(); AddChatThreadMembersOptions options = ChatOptionsProvider.addThreadMembersOptions( firstAddedThreadMember.getId(), secondAddedThreadMember.getId()); StepVerifier.create(chatThreadClient.addMembers(options)) .assertNext(noResp -> { PagedIterable<ChatThreadMember> membersResponse = new PagedIterable<>(chatThreadClient.listMembers()); List<ChatThreadMember> returnedMembers = new ArrayList<ChatThreadMember>(); membersResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedMembers.add(item)); }); for (ChatThreadMember member: options.getMembers()) { assertTrue(checkMembersListContainsMemberId(returnedMembers, member.getUser().getId())); } assertTrue(returnedMembers.size() == 4); }); for (ChatThreadMember member: options.getMembers()) { StepVerifier.create(chatThreadClient.removeMember(member.getUser())) .verifyComplete(); } } @Test public void canAddListAndRemoveMembersWithResponseAsync() throws InterruptedException { firstAddedThreadMember = communicationClient.createUser(); secondAddedThreadMember = communicationClient.createUser(); AddChatThreadMembersOptions options = ChatOptionsProvider.addThreadMembersOptions( firstAddedThreadMember.getId(), secondAddedThreadMember.getId()); StepVerifier.create(chatThreadClient.addMembersWithResponse(options)) .assertNext(addMembersResponse -> { assertEquals(addMembersResponse.getStatusCode(), 207); PagedIterable<ChatThreadMember> membersResponse = new PagedIterable<>(chatThreadClient.listMembers()); List<ChatThreadMember> returnedMembers = new ArrayList<ChatThreadMember>(); membersResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedMembers.add(item)); }); for (ChatThreadMember member: options.getMembers()) { assertTrue(checkMembersListContainsMemberId(returnedMembers, member.getUser().getId())); } assertTrue(returnedMembers.size() == 4); for (ChatThreadMember member: options.getMembers()) { StepVerifier.create(chatThreadClient.removeMemberWithResponse(member.getUser())) .assertNext(resp -> { assertEquals(resp.getStatusCode(), 204); }) .verifyComplete(); } }) .verifyComplete(); } @Test public void canSendThenGetMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create(chatThreadClient.sendMessage(messageRequest)) .assertNext(response -> { StepVerifier.create(chatThreadClient.getMessage(response.getId())) .assertNext(message -> { assertEquals(message.getContent(), messageRequest.getContent()); assertEquals(message.getPriority(), messageRequest.getPriority()); assertEquals(message.getSenderDisplayName(), messageRequest.getSenderDisplayName()); }) .verifyComplete(); }) .verifyComplete(); } @Test public void canSendThenGetMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create(chatThreadClient.sendMessageWithResponse(messageRequest)) .assertNext(sendResponse -> { StepVerifier.create(chatThreadClient.getMessageWithResponse(sendResponse.getValue().getId())) .assertNext(getResponse -> { ChatMessage message = getResponse.getValue(); assertEquals(message.getContent(), messageRequest.getContent()); assertEquals(message.getPriority(), messageRequest.getPriority()); assertEquals(message.getSenderDisplayName(), messageRequest.getSenderDisplayName()); }) .verifyComplete(); }) .verifyComplete(); } @Test @Test public void canDeleteExistingMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.deleteMessageWithResponse(response.getId())) .assertNext(deleteResponse -> { assertEquals(deleteResponse.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canUpdateExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); UpdateChatMessageOptions updateMessageRequest = ChatOptionsProvider.updateMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.updateMessage(response.getId(), updateMessageRequest)) .assertNext(noResp -> { StepVerifier.create(chatThreadClient.getMessage(response.getId())) .assertNext(message -> { assertEquals(message.getContent(), updateMessageRequest.getContent()); }) .verifyComplete(); }); } @Test public void canUpdateExistingMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); UpdateChatMessageOptions updateMessageRequest = ChatOptionsProvider.updateMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.updateMessageWithResponse(response.getId(), updateMessageRequest)) .assertNext(updateResponse -> { assertEquals(updateResponse.getStatusCode(), 200); StepVerifier.create(chatThreadClient.getMessage(response.getId())) .assertNext(message -> { assertEquals(message.getContent(), updateMessageRequest.getContent()); }) .verifyComplete(); }) .verifyComplete(); } @Test public void canListMessages() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); chatThreadClient.sendMessage(messageRequest).block(); chatThreadClient.sendMessage(messageRequest).block(); PagedIterable<ChatMessage> messagesResponse = new PagedIterable<ChatMessage>(chatThreadClient.listMessages()); List<ChatMessage> returnedMessages = new ArrayList<ChatMessage>(); messagesResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> { if (item.getType().equals("Text")) { returnedMessages.add(item); } }); }); assertTrue(returnedMessages.size() == 2); } @Test public void canListMessagesWithOptions() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); chatThreadClient.sendMessage(messageRequest).block(); chatThreadClient.sendMessage(messageRequest).block(); ListChatMessagesOptions options = new ListChatMessagesOptions(); options.setMaxPageSize(10); options.setStartTime(OffsetDateTime.parse("2020-09-08T01:02:14.387Z")); PagedIterable<ChatMessage> messagesResponse = new PagedIterable<ChatMessage>(chatThreadClient.listMessages(options)); List<ChatMessage> returnedMessages = new ArrayList<ChatMessage>(); messagesResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> { if (item.getType().equals("Text")) { returnedMessages.add(item); } }); }); assertTrue(returnedMessages.size() == 2); } @Test public void canSendTypingNotification() { StepVerifier.create(chatThreadClient.sendTypingNotification()) .verifyComplete(); } @Test public void canSendTypingNotificationWithResponse() { StepVerifier.create(chatThreadClient.sendTypingNotificationWithResponse()) .assertNext(response -> { assertEquals(response.getStatusCode(), 200); }) .verifyComplete(); } @Test public void canSendThenListReadReceipts() throws InterruptedException { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.sendReadReceipt(response.getId())) .assertNext(noResp -> { PagedIterable<ReadReceipt> readReceiptsResponse = new PagedIterable<ReadReceipt>(chatThreadClient.listReadReceipts()); List<ReadReceipt> returnedReadReceipts = new ArrayList<ReadReceipt>(); readReceiptsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedReadReceipts.add(item)); }); if (interceptorManager.isPlaybackMode()) { assertTrue(returnedReadReceipts.size() > 0); checkReadReceiptListContainsMessageId(returnedReadReceipts, response.getId()); } }); } @Test public void canSendThenListReadReceiptsWithResponse() throws InterruptedException { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.sendReadReceiptWithResponse(response.getId())) .assertNext(receiptResponse -> { assertEquals(receiptResponse.getStatusCode(), 201); PagedIterable<ReadReceipt> readReceiptsResponse = new PagedIterable<ReadReceipt>(chatThreadClient.listReadReceipts()); List<ReadReceipt> returnedReadReceipts = new ArrayList<ReadReceipt>(); readReceiptsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedReadReceipts.add(item)); }); if (interceptorManager.isPlaybackMode()) { assertTrue(returnedReadReceipts.size() > 0); checkReadReceiptListContainsMessageId(returnedReadReceipts, response.getId()); } }) .verifyComplete(); } }
class ChatThreadAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatThreadAsyncClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private ChatThreadAsyncClient chatThreadClient; private String threadId; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; private CommunicationUser firstAddedThreadMember; private CommunicationUser secondAddedThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions(firstThreadMember.getId(), secondThreadMember.getId()); chatThreadClient = client.createChatThread(threadRequest).block(); threadId = chatThreadClient.getChatThreadId(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canUpdateThread() { UpdateChatThreadOptions threadRequest = ChatOptionsProvider.updateThreadOptions(); StepVerifier.create( chatThreadClient.updateChatThread(threadRequest) .flatMap(noResp -> { return client.getChatThread(threadId); }) ) .assertNext(chatThread -> { assertEquals(chatThread.getTopic(), threadRequest.getTopic()); }); } @Test public void canUpdateThreadWithResponse() { UpdateChatThreadOptions threadRequest = ChatOptionsProvider.updateThreadOptions(); StepVerifier.create( chatThreadClient.updateChatThreadWithResponse(threadRequest) .flatMap(updateThreadResponse -> { assertEquals(updateThreadResponse.getStatusCode(), 200); return client.getChatThread(threadId); }) ) .assertNext(chatThread -> { assertEquals(chatThread.getTopic(), threadRequest.getTopic()); }) .verifyComplete(); } @Test public void canAddListAndRemoveMembersAsync() throws InterruptedException { firstAddedThreadMember = communicationClient.createUser(); secondAddedThreadMember = communicationClient.createUser(); AddChatThreadMembersOptions options = ChatOptionsProvider.addThreadMembersOptions( firstAddedThreadMember.getId(), secondAddedThreadMember.getId()); StepVerifier.create(chatThreadClient.addMembers(options)) .assertNext(noResp -> { PagedIterable<ChatThreadMember> membersResponse = new PagedIterable<>(chatThreadClient.listMembers()); List<ChatThreadMember> returnedMembers = new ArrayList<ChatThreadMember>(); membersResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedMembers.add(item)); }); for (ChatThreadMember member: options.getMembers()) { assertTrue(checkMembersListContainsMemberId(returnedMembers, member.getUser().getId())); } assertTrue(returnedMembers.size() == 4); }); for (ChatThreadMember member: options.getMembers()) { StepVerifier.create(chatThreadClient.removeMember(member.getUser())) .verifyComplete(); } } @Test public void canAddListAndRemoveMembersWithResponseAsync() throws InterruptedException { firstAddedThreadMember = communicationClient.createUser(); secondAddedThreadMember = communicationClient.createUser(); AddChatThreadMembersOptions options = ChatOptionsProvider.addThreadMembersOptions( firstAddedThreadMember.getId(), secondAddedThreadMember.getId()); StepVerifier.create(chatThreadClient.addMembersWithResponse(options)) .assertNext(addMembersResponse -> { assertEquals(addMembersResponse.getStatusCode(), 207); PagedIterable<ChatThreadMember> membersResponse = new PagedIterable<>(chatThreadClient.listMembers()); List<ChatThreadMember> returnedMembers = new ArrayList<ChatThreadMember>(); membersResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedMembers.add(item)); }); for (ChatThreadMember member: options.getMembers()) { assertTrue(checkMembersListContainsMemberId(returnedMembers, member.getUser().getId())); } assertTrue(returnedMembers.size() == 4); }) .verifyComplete(); for (ChatThreadMember member: options.getMembers()) { StepVerifier.create(chatThreadClient.removeMemberWithResponse(member.getUser())) .assertNext(resp -> { assertEquals(resp.getStatusCode(), 204); }) .verifyComplete(); } } @Test public void canSendThenGetMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier .create(chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { return chatThreadClient.getMessage(response.getId()); }) ) .assertNext(message -> { assertEquals(message.getContent(), messageRequest.getContent()); assertEquals(message.getPriority(), messageRequest.getPriority()); assertEquals(message.getSenderDisplayName(), messageRequest.getSenderDisplayName()); }) .verifyComplete(); } @Test public void canSendThenGetMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier .create(chatThreadClient.sendMessageWithResponse(messageRequest) .flatMap(sendResponse -> { assertEquals(sendResponse.getStatusCode(), 201); return chatThreadClient.getMessageWithResponse(sendResponse.getValue().getId()); }) ) .assertNext(getResponse -> { ChatMessage message = getResponse.getValue(); assertEquals(message.getContent(), messageRequest.getContent()); assertEquals(message.getPriority(), messageRequest.getPriority()); assertEquals(message.getSenderDisplayName(), messageRequest.getSenderDisplayName()); }) .verifyComplete(); } @Test @Test public void canDeleteExistingMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { return chatThreadClient.deleteMessageWithResponse(response.getId()); }) ) .assertNext(deleteResponse -> { assertEquals(deleteResponse.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canUpdateExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); UpdateChatMessageOptions updateMessageRequest = ChatOptionsProvider.updateMessageOptions(); AtomicReference<SendChatMessageResult> messageResponseRef = new AtomicReference<>(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { messageResponseRef.set(response); return chatThreadClient.updateMessage(response.getId(), updateMessageRequest); }) .flatMap((Void resp) -> { return chatThreadClient.getMessage(messageResponseRef.get().getId()); }) ) .assertNext(message -> { assertEquals(message.getContent(), updateMessageRequest.getContent()); }); } @Test public void canUpdateExistingMessageWithResponse() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); UpdateChatMessageOptions updateMessageRequest = ChatOptionsProvider.updateMessageOptions(); AtomicReference<SendChatMessageResult> messageResponseRef = new AtomicReference<>(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap((SendChatMessageResult response) -> { messageResponseRef.set(response); return chatThreadClient.updateMessageWithResponse(response.getId(), updateMessageRequest); }) .flatMap((Response<Void> updateResponse) -> { assertEquals(updateResponse.getStatusCode(), 200); return chatThreadClient.getMessage(messageResponseRef.get().getId()); }) ) .assertNext(message -> { assertEquals(message.getContent(), updateMessageRequest.getContent()); }) .verifyComplete(); } @Test public void canListMessages() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .concatWith(chatThreadClient.sendMessage(messageRequest)) ) .assertNext((message) -> { PagedIterable<ChatMessage> messagesResponse = new PagedIterable<ChatMessage>(chatThreadClient.listMessages()); List<ChatMessage> returnedMessages = new ArrayList<ChatMessage>(); messagesResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> { if (item.getType().equals("Text")) { returnedMessages.add(item); } }); }); assertTrue(returnedMessages.size() == 2); }); } @Test public void canListMessagesWithOptions() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); ListChatMessagesOptions options = new ListChatMessagesOptions(); options.setMaxPageSize(10); options.setStartTime(OffsetDateTime.parse("2020-09-08T01:02:14.387Z")); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .concatWith(chatThreadClient.sendMessage(messageRequest))) .assertNext((message) -> { PagedIterable<ChatMessage> messagesResponse = new PagedIterable<ChatMessage>(chatThreadClient.listMessages(options)); List<ChatMessage> returnedMessages = new ArrayList<ChatMessage>(); messagesResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> { if (item.getType().equals("Text")) { returnedMessages.add(item); } }); }); assertTrue(returnedMessages.size() == 2); }); } @Test public void canSendTypingNotification() { StepVerifier.create(chatThreadClient.sendTypingNotification()) .verifyComplete(); } @Test public void canSendTypingNotificationWithResponse() { StepVerifier.create(chatThreadClient.sendTypingNotificationWithResponse()) .assertNext(response -> { assertEquals(response.getStatusCode(), 200); }) .verifyComplete(); } @Test public void canSendThenListReadReceipts() throws InterruptedException { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); AtomicReference<SendChatMessageResult> messageResponseRef = new AtomicReference<>(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { messageResponseRef.set(response); return chatThreadClient.sendReadReceipt(response.getId()); }) ) .assertNext(noResp -> { PagedIterable<ReadReceipt> readReceiptsResponse = new PagedIterable<ReadReceipt>(chatThreadClient.listReadReceipts()); List<ReadReceipt> returnedReadReceipts = new ArrayList<ReadReceipt>(); readReceiptsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedReadReceipts.add(item)); }); if (interceptorManager.isPlaybackMode()) { assertTrue(returnedReadReceipts.size() > 0); checkReadReceiptListContainsMessageId(returnedReadReceipts, messageResponseRef.get().getId()); } }); } @Test public void canSendThenListReadReceiptsWithResponse() throws InterruptedException { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); AtomicReference<SendChatMessageResult> messageResponseRef = new AtomicReference<>(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { messageResponseRef.set(response); return chatThreadClient.sendReadReceiptWithResponse(response.getId()); }) ) .assertNext(receiptResponse -> { assertEquals(receiptResponse.getStatusCode(), 201); PagedIterable<ReadReceipt> readReceiptsResponse = new PagedIterable<ReadReceipt>(chatThreadClient.listReadReceipts()); List<ReadReceipt> returnedReadReceipts = new ArrayList<ReadReceipt>(); readReceiptsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedReadReceipts.add(item)); }); if (interceptorManager.isPlaybackMode()) { assertTrue(returnedReadReceipts.size() > 0); checkReadReceiptListContainsMessageId(returnedReadReceipts, messageResponseRef.get().getId()); } }) .verifyComplete(); } }
Done
public void canGetExistingChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.getChatThread(chatThreadClient.getChatThreadId())) .assertNext(chatThread -> { assertEquals(chatThreadClient.getChatThreadId(), chatThread.getId()); }) .verifyComplete(); }
ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block();
public void canGetExistingChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.getChatThread(chatThreadClient.getChatThreadId()); })) .assertNext(chatThread -> { assertEquals(chatThreadClientRef.get().getChatThreadId(), chatThread.getId()); }) .verifyComplete(); }
class ChatAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); assertNotNull(communicationClient); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canCreateThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThread(threadRequest)) .assertNext(chatThreadClient -> { assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canCreateThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThreadWithResponse(threadRequest)) .assertNext(chatThreadClientResponse -> { ChatThreadAsyncClient chatThreadClient = chatThreadClientResponse.getValue(); assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canGetChatThreadClient() { String threadId = "19:fe0a2f65a7834185b29164a7de57699c@thread.v2"; ChatThreadAsyncClient chatThreadClient = client.getChatThreadClient(threadId); assertNotNull(chatThreadClient); assertEquals(chatThreadClient.getChatThreadId(), threadId); } @Test @Test public void canGetExistingChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.getChatThreadWithResponse(chatThreadClient.getChatThreadId())) .assertNext(chatThreadResponse -> { ChatThread chatThread = chatThreadResponse.getValue(); assertEquals(chatThreadClient.getChatThreadId(), chatThread.getId()); }) .verifyComplete(); } @Test public void getNotFoundOnNonExistingChatThread() { StepVerifier.create(client.getChatThread("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void getNotFoundOnNonExistingChatThreadWithResponse() { StepVerifier.create(client.getChatThreadWithResponse("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void canDeleteChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.deleteChatThread(chatThreadClient.getChatThreadId())) .verifyComplete(); } @Test public void canDeleteChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ChatThreadAsyncClient chatThreadClient = client.createChatThread(threadRequest).block(); StepVerifier.create(client.deleteChatThreadWithResponse(chatThreadClient.getChatThreadId())) .assertNext(response -> { assertEquals(response.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canListChatThreads() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); client.createChatThread(threadRequest).block(); client.createChatThread(threadRequest).block(); Thread.sleep(500); PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads()); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); } @Test public void canListChatThreadsWithMaxPageSize() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); client.createChatThread(threadRequest).block(); client.createChatThread(threadRequest).block(); Thread.sleep(500); ListChatThreadsOptions options = new ListChatThreadsOptions(); options.setMaxPageSize(10); PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads(options)); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); } }
class ChatAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private CommunicationUser firstThreadMember; private CommunicationUser secondThreadMember; @Override protected void beforeTest() { super.beforeTest(); communicationClient = getCommunicationIdentityClientBuilder().buildClient(); assertNotNull(communicationClient); firstThreadMember = communicationClient.createUser(); secondThreadMember = communicationClient.createUser(); List<String> scopes = new ArrayList<String>(Arrays.asList("chat")); CommunicationUserToken response = communicationClient.issueToken(firstThreadMember, scopes); client = getChatClientBuilder(response.getToken()).buildAsyncClient(); } @Override protected void afterTest() { super.afterTest(); } @Test public void canCreateThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThread(threadRequest)) .assertNext(chatThreadClient -> { assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canCreateThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create(client.createChatThreadWithResponse(threadRequest)) .assertNext(chatThreadClientResponse -> { ChatThreadAsyncClient chatThreadClient = chatThreadClientResponse.getValue(); assertNotNull(chatThreadClient); assertNotNull(chatThreadClient.getChatThreadId()); }) .verifyComplete(); } @Test public void canGetChatThreadClient() { String threadId = "19:fe0a2f65a7834185b29164a7de57699c@thread.v2"; ChatThreadAsyncClient chatThreadClient = client.getChatThreadClient(threadId); assertNotNull(chatThreadClient); assertEquals(chatThreadClient.getChatThreadId(), threadId); } @Test @Test public void canGetExistingChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.getChatThreadWithResponse(chatThreadClient.getChatThreadId()); })) .assertNext(chatThreadResponse -> { ChatThread chatThread = chatThreadResponse.getValue(); assertEquals(chatThreadClientRef.get().getChatThreadId(), chatThread.getId()); }) .verifyComplete(); } @Test public void getNotFoundOnNonExistingChatThread() { StepVerifier.create(client.getChatThread("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void getNotFoundOnNonExistingChatThreadWithResponse() { StepVerifier.create(client.getChatThreadWithResponse("19:020082a8df7b44dd8c722bea8fe7167f@thread.v2")) .expectErrorMatches(exception -> ((HttpResponseException) exception).getResponse().getStatusCode() == 404 ) .verify(); } @Test public void canDeleteChatThread() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.deleteChatThread(chatThreadClient.getChatThreadId()); }) ) .verifyComplete(); } @Test public void canDeleteChatThreadWithResponse() { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); AtomicReference<ChatThreadAsyncClient> chatThreadClientRef = new AtomicReference<>(); StepVerifier.create( client.createChatThread(threadRequest) .flatMap(chatThreadClient -> { chatThreadClientRef.set(chatThreadClient); return client.deleteChatThreadWithResponse(chatThreadClient.getChatThreadId()); }) ) .assertNext(deleteResponse -> { assertEquals(deleteResponse.getStatusCode(), 204); }) .verifyComplete(); } @Test public void canListChatThreads() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); StepVerifier.create( client.createChatThread(threadRequest) .concatWith(client.createChatThread(threadRequest))) .assertNext(chatThreadClient -> { PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads()); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); }); } @Test public void canListChatThreadsWithMaxPageSize() throws InterruptedException { CreateChatThreadOptions threadRequest = ChatOptionsProvider.createThreadOptions( firstThreadMember.getId(), secondThreadMember.getId()); ListChatThreadsOptions options = new ListChatThreadsOptions(); options.setMaxPageSize(10); StepVerifier.create( client.createChatThread(threadRequest) .concatWith(client.createChatThread(threadRequest))) .assertNext(chatThreadClient -> { PagedIterable<ChatThreadInfo> threadsResponse = new PagedIterable<>(client.listChatThreads(options)); List<ChatThreadInfo> returnedThreads = new ArrayList<ChatThreadInfo>(); threadsResponse.iterableByPage().forEach(resp -> { assertEquals(resp.getStatusCode(), 200); resp.getItems().forEach(item -> returnedThreads.add(item)); }); assertTrue(returnedThreads.size() == 2); }); } }
Should return an unmodifiable list to the user.
public List<FormSelectionMark> getSelectionMarks() { return this.selectionMarks; }
return this.selectionMarks;
public List<FormSelectionMark> getSelectionMarks() { return Collections.unmodifiableList(this.selectionMarks); }
class FormPage { /* * The height of the image/PDF in pixels/inches, respectively. */ private final float height; /* * When includeFieldElements is set to true, a list of recognized text lines. */ private final List<FormLine> lines; /* * List of data tables extracted from the page. */ private final List<FormTable> tables; /* * List of selection marks extracted from the page. */ private List<FormSelectionMark> selectionMarks; /* * The general orientation of the text in clockwise direction, measured in * degrees between (-180, 180]. */ private final float textAngle; /* * The unit used by the width, height and boundingBox properties. For * images, the unit is "pixel". For PDF, the unit is "inch". */ private final LengthUnit unit; /* * The width of the image/PDF in pixels/inches, respectively. */ private final float width; /* * The 1 based page number. */ private final Integer pageNumber; /** * Constructs a FormPage object. * * @param height The height of the image/PDF in pixels/inches, respectively. * @param textAngle The general orientation of the text in clockwise direction. * @param unit The unit used by the width, height and boundingBox properties. * @param width The width of the image/PDF in pixels/inches, respectively. * @param lines When includeFieldElements is set to true, a list of recognized text lines. * @param tables List of data tables extracted from the page. * @param pageNumber the 1-based page number in the input document. */ public FormPage(final float height, final float textAngle, final LengthUnit unit, final float width, final List<FormLine> lines, final List<FormTable> tables, final int pageNumber) { this.height = height; this.textAngle = textAngle > 180 ? textAngle - 360 : textAngle; this.unit = unit; this.width = width; this.lines = lines == null ? null : Collections.unmodifiableList(lines); this.tables = tables == null ? null : Collections.unmodifiableList(tables); this.pageNumber = pageNumber; } /** * Get the height property: The height of the image/PDF in pixels/inches, * respectively. * * @return the height value. */ public float getHeight() { return this.height; } /** * Get the lines property: When includeFieldElements is set to true, a list * of recognized text lines. * * @return the unmodifiable list of recognized lines. */ public List<FormLine> getLines() { return this.lines; } /** * Get the tables property: List of data tables extracted from the page. * * @return the unmodifiable list of recognized tables. */ public List<FormTable> getTables() { return this.tables; } /** * Get the text angle property. * * @return the text angle value. */ public float getTextAngle() { return this.textAngle; } /** * Get the unit property: The unit used by the width, height and * boundingBox properties. For images, the unit is "pixel". For PDF, the * unit is "inch". * * @return the unit value. */ public LengthUnit getUnit() { return this.unit; } /** * Get the width property: The width of the image/PDF in pixels/inches, * respectively. * * @return the width value. */ public float getWidth() { return this.width; } /** * Get the 1-based page number in the input document. * * @return the page number value. */ public Integer getPageNumber() { return this.pageNumber; } /** * Get the selection marks in the input document. * * @return the selection marks. */ }
class FormPage { /* * The height of the image/PDF in pixels/inches, respectively. */ private final float height; /* * When includeFieldElements is set to true, a list of recognized text lines. */ private final List<FormLine> lines; /* * List of data tables extracted from the page. */ private final List<FormTable> tables; /* * List of selection marks extracted from the page. */ private List<FormSelectionMark> selectionMarks; /* * The general orientation of the text in clockwise direction, measured in * degrees between (-180, 180]. */ private final float textAngle; /* * The unit used by the width, height and boundingBox properties. For * images, the unit is "pixel". For PDF, the unit is "inch". */ private final LengthUnit unit; /* * The width of the image/PDF in pixels/inches, respectively. */ private final float width; /* * The 1 based page number. */ private final Integer pageNumber; /** * Constructs a FormPage object. * * @param height The height of the image/PDF in pixels/inches, respectively. * @param textAngle The general orientation of the text in clockwise direction. * @param unit The unit used by the width, height and boundingBox properties. * @param width The width of the image/PDF in pixels/inches, respectively. * @param lines When includeFieldElements is set to true, a list of recognized text lines. * @param tables List of data tables extracted from the page. * @param pageNumber the 1-based page number in the input document. */ public FormPage(final float height, final float textAngle, final LengthUnit unit, final float width, final List<FormLine> lines, final List<FormTable> tables, final int pageNumber) { this.height = height; this.textAngle = textAngle > 180 ? textAngle - 360 : textAngle; this.unit = unit; this.width = width; this.lines = lines == null ? null : Collections.unmodifiableList(lines); this.tables = tables == null ? null : Collections.unmodifiableList(tables); this.pageNumber = pageNumber; } /** * Get the height property: The height of the image/PDF in pixels/inches, * respectively. * * @return the height value. */ public float getHeight() { return this.height; } /** * Get the lines property: When includeFieldElements is set to true, a list * of recognized text lines. * * @return the unmodifiable list of recognized lines. */ public List<FormLine> getLines() { return this.lines; } /** * Get the tables property: List of data tables extracted from the page. * * @return the unmodifiable list of recognized tables. */ public List<FormTable> getTables() { return this.tables; } /** * Get the text angle property. * * @return the text angle value. */ public float getTextAngle() { return this.textAngle; } /** * Get the unit property: The unit used by the width, height and * boundingBox properties. For images, the unit is "pixel". For PDF, the * unit is "inch". * * @return the unit value. */ public LengthUnit getUnit() { return this.unit; } /** * Get the width property: The width of the image/PDF in pixels/inches, * respectively. * * @return the width value. */ public float getWidth() { return this.width; } /** * Get the 1-based page number in the input document. * * @return the page number value. */ public Integer getPageNumber() { return this.pageNumber; } /** * Get the selection marks in the input document. * * @return the selection marks. */ }
This `validateAndThrow(prefetch)` , in other PR we were validating earlier when user is setting prefetch . Should't this go there.
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, subQueue); validateAndThrow(prefetchCount); if (!isAutoCompleteAllowed && enableAutoComplete) { throw new IllegalStateException("'enableAutoComplete' is not support in synchronous client."); } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, enableAutoComplete); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); }
validateAndThrow(prefetchCount);
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); if (!isAutoCompleteAllowed && enableAutoComplete) { logger.warning( "'enableAutoComplete' is not supported in synchronous client except through callback receive."); enableAutoComplete = false; } else if (enableAutoComplete && receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { throw logger.logExceptionAsError(new IllegalStateException( "'enableAutoComplete' is not valid for RECEIVE_AND_DELETE mode.")); } if (receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { maxAutoLockRenewDuration = Duration.ZERO; } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, maxAutoLockRenewDuration, enableAutoComplete, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); }
class ServiceBusReceiverClientBuilder { private boolean enableAutoComplete = false; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private SubQueue subQueue; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String subscriptionName; private String topicName; private ServiceBusReceiverClientBuilder() { } /** * Enables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is * {@link ServiceBusReceiverAsyncClient * * @param enableAutoComplete True to enable auto-complete and false otherwise. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder enableAutoComplete(boolean enableAutoComplete) { this.enableAutoComplete = enableAutoComplete; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the type of the {@link SubQueue} to connect to. * * @param subQueue The type of the sub queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) { this.subQueue = subQueue; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage * messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages} * from a specific queue or topic. * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); } }
class ServiceBusSessionReceiverClientBuilder { private boolean enableAutoComplete = true; private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION; private ServiceBusSessionReceiverClientBuilder() { } /** * Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is {@link ServiceBusReceiverAsyncClient * abandoned}. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder disableAutoComplete() { this.enableAutoComplete = false; return this; } /** * Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration * {@code null} disables auto-renewal. For {@link ReceiveMode * auto-renewal is disabled. * * @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock. * {@link Duration * * @return The updated {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative. */ public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) { validateAndThrow(maxAutoLockRenewDuration); this.maxAutoLockRenewDuration = maxAutoLockRenewDuration; return this; } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch * off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code prefetchCount} is negative. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { validateAndThrow(prefetchCount); this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); } private /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } }
I thought that we are also doing this for sync clients ?
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, subQueue); validateAndThrow(prefetchCount); if (!isAutoCompleteAllowed && enableAutoComplete) { throw new IllegalStateException("'enableAutoComplete' is not support in synchronous client."); } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, enableAutoComplete); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); }
throw new IllegalStateException("'enableAutoComplete' is not support in synchronous client.");
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); if (!isAutoCompleteAllowed && enableAutoComplete) { logger.warning( "'enableAutoComplete' is not supported in synchronous client except through callback receive."); enableAutoComplete = false; } else if (enableAutoComplete && receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { throw logger.logExceptionAsError(new IllegalStateException( "'enableAutoComplete' is not valid for RECEIVE_AND_DELETE mode.")); } if (receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { maxAutoLockRenewDuration = Duration.ZERO; } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, maxAutoLockRenewDuration, enableAutoComplete, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); }
class ServiceBusReceiverClientBuilder { private boolean enableAutoComplete = false; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private SubQueue subQueue; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String subscriptionName; private String topicName; private ServiceBusReceiverClientBuilder() { } /** * Enables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is * {@link ServiceBusReceiverAsyncClient * * @param enableAutoComplete True to enable auto-complete and false otherwise. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder enableAutoComplete(boolean enableAutoComplete) { this.enableAutoComplete = enableAutoComplete; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the type of the {@link SubQueue} to connect to. * * @param subQueue The type of the sub queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) { this.subQueue = subQueue; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage * messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages} * from a specific queue or topic. * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); } }
class ServiceBusSessionReceiverClientBuilder { private boolean enableAutoComplete = true; private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION; private ServiceBusSessionReceiverClientBuilder() { } /** * Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is {@link ServiceBusReceiverAsyncClient * abandoned}. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder disableAutoComplete() { this.enableAutoComplete = false; return this; } /** * Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration * {@code null} disables auto-renewal. For {@link ReceiveMode * auto-renewal is disabled. * * @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock. * {@link Duration * * @return The updated {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative. */ public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) { validateAndThrow(maxAutoLockRenewDuration); this.maxAutoLockRenewDuration = maxAutoLockRenewDuration; return this; } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch * off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code prefetchCount} is negative. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { validateAndThrow(prefetchCount); this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); } private /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } }
Yes. It's for the callback model. The pull model will not have that.
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, subQueue); validateAndThrow(prefetchCount); if (!isAutoCompleteAllowed && enableAutoComplete) { throw new IllegalStateException("'enableAutoComplete' is not support in synchronous client."); } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, enableAutoComplete); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); }
throw new IllegalStateException("'enableAutoComplete' is not support in synchronous client.");
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); if (!isAutoCompleteAllowed && enableAutoComplete) { logger.warning( "'enableAutoComplete' is not supported in synchronous client except through callback receive."); enableAutoComplete = false; } else if (enableAutoComplete && receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { throw logger.logExceptionAsError(new IllegalStateException( "'enableAutoComplete' is not valid for RECEIVE_AND_DELETE mode.")); } if (receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { maxAutoLockRenewDuration = Duration.ZERO; } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, maxAutoLockRenewDuration, enableAutoComplete, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); }
class ServiceBusReceiverClientBuilder { private boolean enableAutoComplete = false; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private SubQueue subQueue; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String subscriptionName; private String topicName; private ServiceBusReceiverClientBuilder() { } /** * Enables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is * {@link ServiceBusReceiverAsyncClient * * @param enableAutoComplete True to enable auto-complete and false otherwise. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder enableAutoComplete(boolean enableAutoComplete) { this.enableAutoComplete = enableAutoComplete; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. */ public ServiceBusReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the type of the {@link SubQueue} to connect to. * * @param subQueue The type of the sub queue. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) { this.subQueue = subQueue; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusReceiverClientBuilder} object. * @see */ public ServiceBusReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage * messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages} * from a specific queue or topic. * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); } }
class ServiceBusSessionReceiverClientBuilder { private boolean enableAutoComplete = true; private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION; private ServiceBusSessionReceiverClientBuilder() { } /** * Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is {@link ServiceBusReceiverAsyncClient * abandoned}. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder disableAutoComplete() { this.enableAutoComplete = false; return this; } /** * Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration * {@code null} disables auto-renewal. For {@link ReceiveMode * auto-renewal is disabled. * * @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock. * {@link Duration * * @return The updated {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative. */ public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) { validateAndThrow(maxAutoLockRenewDuration); this.maxAutoLockRenewDuration = maxAutoLockRenewDuration; return this; } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch * off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code prefetchCount} is negative. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { validateAndThrow(prefetchCount); this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); } private /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } }
For the processor, autocomplete should still be possible right? So, the async client has to be built with autocomplete enabled by default.
public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); }
return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout());
public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); }
class ServiceBusSessionReceiverClientBuilder { private boolean enableAutoComplete = true; private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private ServiceBusSessionReceiverClientBuilder() { } /** * Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is {@link ServiceBusReceiverAsyncClient * abandoned}. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder disableAutoComplete() { this.enableAutoComplete = false; return this; } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch * off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ private ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); validateAndThrow(prefetchCount); if (!isAutoCompleteAllowed && enableAutoComplete) { logger.warning( "'enableAutoComplete' is not supported in synchronous client except through callback receive."); enableAutoComplete = false; } else if (isAutoCompleteAllowed && receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { throw logger.logExceptionAsError(new IllegalStateException( "'enableAutoComplete' is not valid for RECEIVE_AND_DELETE mode.")); } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, enableAutoComplete, sessionId, isRollingSessionReceiver(), maxConcurrentSessions, true); if (CoreUtils.isNullOrEmpty(sessionId)) { final UnnamedSessionManager sessionManager = new UnnamedSessionManager(entityPath, entityType, connectionProcessor, connectionProcessor.getRetryOptions().getTryTimeout(), tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); } else { return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } } /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } }
class ServiceBusSessionReceiverClientBuilder { private boolean enableAutoComplete = true; private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION; private ServiceBusSessionReceiverClientBuilder() { } /** * Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is {@link ServiceBusReceiverAsyncClient * abandoned}. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder disableAutoComplete() { this.enableAutoComplete = false; return this; } /** * Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration * {@code null} disables auto-renewal. For {@link ReceiveMode * auto-renewal is disabled. * * @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock. * {@link Duration * * @return The updated {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative. */ public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) { validateAndThrow(maxAutoLockRenewDuration); this.maxAutoLockRenewDuration = maxAutoLockRenewDuration; return this; } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch * off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code prefetchCount} is negative. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { validateAndThrow(prefetchCount); this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ private ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); if (!isAutoCompleteAllowed && enableAutoComplete) { logger.warning( "'enableAutoComplete' is not supported in synchronous client except through callback receive."); enableAutoComplete = false; } else if (enableAutoComplete && receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { throw logger.logExceptionAsError(new IllegalStateException( "'enableAutoComplete' is not valid for RECEIVE_AND_DELETE mode.")); } if (receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { maxAutoLockRenewDuration = Duration.ZERO; } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, maxAutoLockRenewDuration, enableAutoComplete, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); } /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } }
Same as above. Async client should be built with autocomplete enabled for the processor. We may have to find a different way to disable it on the `receive()` method on the sync client.
public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); }
return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout());
public ServiceBusReceiverClient buildClient() { return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout()); }
class ServiceBusSessionReceiverClientBuilder { private boolean enableAutoComplete = true; private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private ServiceBusSessionReceiverClientBuilder() { } /** * Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is {@link ServiceBusReceiverAsyncClient * abandoned}. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder disableAutoComplete() { this.enableAutoComplete = false; return this; } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch * off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ private ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); validateAndThrow(prefetchCount); if (!isAutoCompleteAllowed && enableAutoComplete) { logger.warning( "'enableAutoComplete' is not supported in synchronous client except through callback receive."); enableAutoComplete = false; } else if (isAutoCompleteAllowed && receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { throw logger.logExceptionAsError(new IllegalStateException( "'enableAutoComplete' is not valid for RECEIVE_AND_DELETE mode.")); } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, enableAutoComplete, sessionId, isRollingSessionReceiver(), maxConcurrentSessions, true); if (CoreUtils.isNullOrEmpty(sessionId)) { final UnnamedSessionManager sessionManager = new UnnamedSessionManager(entityPath, entityType, connectionProcessor, connectionProcessor.getRetryOptions().getTryTimeout(), tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); } else { return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); } } /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } }
class ServiceBusSessionReceiverClientBuilder { private boolean enableAutoComplete = true; private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String subscriptionName; private String topicName; private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION; private ServiceBusSessionReceiverClientBuilder() { } /** * Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is * {@link ServiceBusReceiverAsyncClient * the message is processed, it is {@link ServiceBusReceiverAsyncClient * abandoned}. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder disableAutoComplete() { this.enableAutoComplete = false; return this; } /** * Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration * {@code null} disables auto-renewal. For {@link ReceiveMode * auto-renewal is disabled. * * @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock. * {@link Duration * * @return The updated {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative. */ public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) { validateAndThrow(maxAutoLockRenewDuration); this.maxAutoLockRenewDuration = maxAutoLockRenewDuration; return this; } /** * Enables session processing roll-over by processing at most {@code maxConcurrentSessions}. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError(new IllegalArgumentException( "maxConcurrentSessions cannot be less than 1.")); } this.maxConcurrentSessions = maxConcurrentSessions; return this; } /** * Sets the prefetch count of the receiver. For both {@link ReceiveMode * ReceiveMode * * Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when * and before the application asks for one using {@link ServiceBusReceiverAsyncClient * Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch * off. * * @param prefetchCount The prefetch count. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @throws IllegalArgumentException If {code prefetchCount} is negative. */ public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) { validateAndThrow(prefetchCount); this.prefetchCount = prefetchCount; return this; } /** * Sets the name of the queue to create a receiver for. * * @param queueName Name of the queue. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder queueName(String queueName) { this.queueName = queueName; return this; } /** * Sets the receive mode for the receiver. * * @param receiveMode Mode for receiving messages. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder receiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; return this; } /** * Sets the session id. * * @param sessionId session id. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. */ public ServiceBusSessionReceiverClientBuilder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the name of the subscription in the topic to listen to. <b>{@link * </b> * * @param subscriptionName Name of the subscription. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; return this; } /** * Sets the name of the topic. <b>{@link * * @param topicName Name of the topic. * * @return The modified {@link ServiceBusSessionReceiverClientBuilder} object. * @see */ public ServiceBusSessionReceiverClientBuilder topicName(String topicName) { this.topicName = topicName; return this; } /** * Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ public ServiceBusReceiverAsyncClient buildAsyncClient() { return buildAsyncClient(true); } /** * Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link * ServiceBusMessage messages} from a specific queue or topic. * * @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or topic. * @throws IllegalStateException if {@link * topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link * * {@link * * @throws IllegalArgumentException Queue or topic name are not set via {@link * queueName()} or {@link */ private ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, SubQueue.NONE); if (!isAutoCompleteAllowed && enableAutoComplete) { logger.warning( "'enableAutoComplete' is not supported in synchronous client except through callback receive."); enableAutoComplete = false; } else if (enableAutoComplete && receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { throw logger.logExceptionAsError(new IllegalStateException( "'enableAutoComplete' is not valid for RECEIVE_AND_DELETE mode.")); } if (receiveMode == ReceiveMode.RECEIVE_AND_DELETE) { maxAutoLockRenewDuration = Duration.ZERO; } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, maxAutoLockRenewDuration, enableAutoComplete, sessionId, isRollingSessionReceiver(), maxConcurrentSessions); final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager); } /** * This is a rolling session receiver only if maxConcurrentSessions is > 0 AND sessionId is null or empty. If * there is a sessionId, this is going to be a single, named session receiver. * * @return {@code true} if this is an unnamed rolling session receiver; {@code false} otherwise. */ private boolean isRollingSessionReceiver() { if (maxConcurrentSessions == null) { return false; } if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } return CoreUtils.isNullOrEmpty(sessionId); } }
delete it because nowhere is using this method.
static SerializerAdapter getSerializerAdapter() { return JacksonAdapter.createDefaultSerializerAdapter(); }
return JacksonAdapter.createDefaultSerializerAdapter();
static SerializerAdapter getSerializerAdapter() { return JacksonAdapter.createDefaultSerializerAdapter(); }
class TestUtils { static final Duration ONE_NANO_DURATION = Duration.ofNanos(1); static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); static final String BLANK_PDF = "blank.pdf"; static final String FORM_JPG = "Form_1.jpg"; static final String TEST_DATA_PNG = "testData.png"; static final String SELECTION_MARK_PDF = "selectionMarkForm.pdf"; static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; static final String FAKE_ENCODED_EMPTY_SPACE_URL = "https: static final String INVALID_IMAGE_URL_ERROR_CODE = "InvalidImageURL"; static final String INVALID_KEY = "invalid key"; static final String INVALID_MODEL_ID = "a0a3998a-4c4affe66b7"; static final String INVALID_MODEL_ID_ERROR = "Invalid UUID string: " + INVALID_MODEL_ID; static final String INVALID_RECEIPT_URL = "https: static final String INVALID_SOURCE_URL_ERROR_CODE = "1003"; static final String INVALID_URL = "htttttttps: static final String NON_EXIST_MODEL_ID = "00000000-0000-0000-0000-000000000000"; static final String NULL_SOURCE_URL_ERROR = "'trainingFilesUrl' cannot be null."; static final String URL_TEST_FILE_FORMAT = "https: + "master/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/sample_files/Test/"; static final String VALID_HTTPS_LOCALHOST = "https: static final String VALID_HTTP_LOCALHOST = "http: static final String VALID_URL = "https: private TestUtils() { } static InputStream getContentDetectionFileData(String localFileUrl) { try { return new FileInputStream(localFileUrl); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(FormRecognizerServiceVersion.values()).filter( TestUtils::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link FormRecognizerServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(FormRecognizerServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get("AZURE_FORM_RECOGNIZER_TEST_SERVICE_VERSIONS"); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return FormRecognizerServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) { return true; } String[] configuredServiceVersionList = serviceVersionFromEnv.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } static void validateExceptionSource(HttpResponseException errorResponseException) { StepVerifier.create(FluxUtil.collectBytesInByteBufferStream( errorResponseException.getResponse().getRequest().getBody())) .assertNext(bytes -> assertEquals(ENCODED_EMPTY_SPACE, new String(bytes, StandardCharsets.UTF_8))) .verifyComplete(); } }
class TestUtils { static final Duration ONE_NANO_DURATION = Duration.ofNanos(1); static final String BLANK_PDF = "blank.pdf"; static final String FORM_JPG = "Form_1.jpg"; static final String TEST_DATA_PNG = "testData.png"; static final String SELECTION_MARK_PDF = "selectionMarkForm.pdf"; static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; static final String FAKE_ENCODED_EMPTY_SPACE_URL = "https: static final String INVALID_IMAGE_URL_ERROR_CODE = "InvalidImageURL"; static final String INVALID_KEY = "invalid key"; static final String INVALID_MODEL_ID = "a0a3998a-4c4affe66b7"; static final String INVALID_MODEL_ID_ERROR = "Invalid UUID string: " + INVALID_MODEL_ID; static final String INVALID_RECEIPT_URL = "https: static final String INVALID_SOURCE_URL_ERROR_CODE = "1003"; static final String INVALID_URL = "htttttttps: static final String NON_EXIST_MODEL_ID = "00000000-0000-0000-0000-000000000000"; static final String NULL_SOURCE_URL_ERROR = "'trainingFilesUrl' cannot be null."; static final String URL_TEST_FILE_FORMAT = "https: + "master/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/sample_files/Test/"; static final String VALID_HTTPS_LOCALHOST = "https: static final String VALID_HTTP_LOCALHOST = "http: static final String VALID_URL = "https: private TestUtils() { } static InputStream getContentDetectionFileData(String localFileUrl) { try { return new FileInputStream(localFileUrl); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(FormRecognizerServiceVersion.values()).filter( TestUtils::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link FormRecognizerServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(FormRecognizerServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get("AZURE_FORM_RECOGNIZER_TEST_SERVICE_VERSIONS"); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return FormRecognizerServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) { return true; } String[] configuredServiceVersionList = serviceVersionFromEnv.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } static void validateExceptionSource(HttpResponseException errorResponseException) { StepVerifier.create(FluxUtil.collectBytesInByteBufferStream( errorResponseException.getResponse().getRequest().getBody())) .assertNext(bytes -> assertEquals(ENCODED_EMPTY_SPACE, new String(bytes, StandardCharsets.UTF_8))) .verifyComplete(); } }
NIT: normalize indentation
public void fitsAllOperations() { List<CosmosItemOperation> operations = new ArrayList<CosmosItemOperation>() {{ createItemBulkOperation(""); createItemBulkOperation(""); }}; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequest.createBatchRequest( "0", operations, 200000, 2); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(operations.size()); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations()).isEqualTo(operations); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()).isZero(); }
200000,
public void fitsAllOperations() { List<CosmosItemOperation> operations = new ArrayList<CosmosItemOperation>() {{ createItemBulkOperation(""); createItemBulkOperation(""); }}; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequest.createBatchRequest( "0", operations, 200000, 2); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(operations.size()); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations()).isEqualTo(operations); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()).isZero(); }
class PartitionKeyRangeServerBatchRequestTests { private static final int TIMEOUT = 40000; private CosmosItemOperation createItemBulkOperation(String id) { ItemBulkOperation<?> operation = new ItemBulkOperation<>( CosmosItemOperationType.CREATE, id, PartitionKey.NONE, null, null ); return operation; } @Test(groups = {"unit"}, timeOut = TIMEOUT) @Test(groups = {"unit"}, timeOut = TIMEOUT) public void overflowsBasedOnCount() { List<CosmosItemOperation> operations = new ArrayList<CosmosItemOperation>() {{ add(createItemBulkOperation("1")); add(createItemBulkOperation("2")); add(createItemBulkOperation("3")); }}; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequest.createBatchRequest( "0", operations, 200000, 0); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(1); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().get(0).getId()).isEqualTo(operations.get(0).getId()); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()).isEqualTo(2); assertThat(serverOperationBatchRequest.getBatchPendingOperations().get(0).getId()).isEqualTo(operations.get(1).getId()); assertThat(serverOperationBatchRequest.getBatchPendingOperations().get(1).getId()).isEqualTo(operations.get(2).getId()); } @Test(groups = {"unit"}, timeOut = TIMEOUT) public void overflowsBasedOnCountWithOffset() { List<CosmosItemOperation> operations = new ArrayList<CosmosItemOperation>() {{ add(createItemBulkOperation("1")); add(createItemBulkOperation("2")); add(createItemBulkOperation("3")); }}; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequest.createBatchRequest( "0", operations.subList(1, 3), 200000, 1); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(1); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().get(0).getId()).isEqualTo(operations.get(1).getId()); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()).isEqualTo(1); assertThat(serverOperationBatchRequest.getBatchPendingOperations().get(0).getId()).isEqualTo(operations.get(2).getId()); } @Test(groups = {"unit"}, timeOut = TIMEOUT * 100) public void partitionKeyRangeServerBatchRequestSizeTests() { int docSizeInBytes = 250; int operationCount = 10; for (int expectedOperationCount : new int[] { 1, 2, 5, 10 }) { PartitionKeyRangeServerBatchRequestTests. verifyServerRequestCreationsBySizeAsync(expectedOperationCount, operationCount, docSizeInBytes); PartitionKeyRangeServerBatchRequestTests. verifyServerRequestCreationsByCountAsync(expectedOperationCount, operationCount, docSizeInBytes); } } private static void verifyServerRequestCreationsBySizeAsync( int expectedOperationCount, int operationCount, int docSizeInBytes) { int perDocOverheadEstimateInBytes = 50; int maxServerRequestBodyLength = (docSizeInBytes + perDocOverheadEstimateInBytes) * expectedOperationCount; int maxServerRequestOperationCount = Integer.MAX_VALUE; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequestTests. getBatchWithCreateOperationsAsync(operationCount, maxServerRequestBodyLength, maxServerRequestOperationCount, docSizeInBytes); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(expectedOperationCount); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()). isEqualTo(operationCount - serverOperationBatchRequest.getBatchRequest().getOperations().size()); } private static void verifyServerRequestCreationsByCountAsync( int expectedOperationCount, int operationCount, int docSizeInBytes) { int maxServerRequestBodyLength = Integer.MAX_VALUE; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequestTests. getBatchWithCreateOperationsAsync(operationCount, maxServerRequestBodyLength, expectedOperationCount, docSizeInBytes); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(expectedOperationCount); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()). isEqualTo(operationCount - serverOperationBatchRequest.getBatchRequest().getOperations().size()); } private static ServerOperationBatchRequest getBatchWithCreateOperationsAsync( int operationCount, int maxServerRequestBodyLength, int maxServerRequestOperationCount, int docSizeInBytes) { List<CosmosItemOperation> operations = new ArrayList<>(); for (int i = 0; i < operationCount; i++) { JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set("abc", StringUtils.repeat("x", docSizeInBytes - 10)); ItemBulkOperation<?> operation = new ItemBulkOperation<>( CosmosItemOperationType.CREATE, "", null, null, jsonSerializable ); operations.add(operation); } return PartitionKeyRangeServerBatchRequest.createBatchRequest( "0", operations, maxServerRequestBodyLength, maxServerRequestOperationCount); } }
class PartitionKeyRangeServerBatchRequestTests { private static final int TIMEOUT = 40000; private CosmosItemOperation createItemBulkOperation(String id) { ItemBulkOperation<?> operation = new ItemBulkOperation<>( CosmosItemOperationType.CREATE, id, PartitionKey.NONE, null, null ); return operation; } @Test(groups = {"unit"}, timeOut = TIMEOUT) @Test(groups = {"unit"}, timeOut = TIMEOUT) public void overflowsBasedOnCount() { List<CosmosItemOperation> operations = new ArrayList<CosmosItemOperation>() {{ add(createItemBulkOperation("1")); add(createItemBulkOperation("2")); add(createItemBulkOperation("3")); }}; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequest.createBatchRequest( "0", operations, 200000, 0); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(1); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().get(0).getId()).isEqualTo(operations.get(0).getId()); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()).isEqualTo(2); assertThat(serverOperationBatchRequest.getBatchPendingOperations().get(0).getId()).isEqualTo(operations.get(1).getId()); assertThat(serverOperationBatchRequest.getBatchPendingOperations().get(1).getId()).isEqualTo(operations.get(2).getId()); } @Test(groups = {"unit"}, timeOut = TIMEOUT) public void overflowsBasedOnCountWithOffset() { List<CosmosItemOperation> operations = new ArrayList<CosmosItemOperation>() {{ add(createItemBulkOperation("1")); add(createItemBulkOperation("2")); add(createItemBulkOperation("3")); }}; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequest.createBatchRequest( "0", operations.subList(1, 3), 200000, 1); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(1); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().get(0).getId()).isEqualTo(operations.get(1).getId()); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()).isEqualTo(1); assertThat(serverOperationBatchRequest.getBatchPendingOperations().get(0).getId()).isEqualTo(operations.get(2).getId()); } @Test(groups = {"unit"}, timeOut = TIMEOUT * 100) public void partitionKeyRangeServerBatchRequestSizeTests() { int docSizeInBytes = 250; int operationCount = 10; for (int expectedOperationCount : new int[] { 1, 2, 5, 10 }) { PartitionKeyRangeServerBatchRequestTests. verifyServerRequestCreationsBySizeAsync(expectedOperationCount, operationCount, docSizeInBytes); PartitionKeyRangeServerBatchRequestTests. verifyServerRequestCreationsByCountAsync(expectedOperationCount, operationCount, docSizeInBytes); } } private static void verifyServerRequestCreationsBySizeAsync( int expectedOperationCount, int operationCount, int docSizeInBytes) { int perDocOverheadEstimateInBytes = 50; int maxServerRequestBodyLength = (docSizeInBytes + perDocOverheadEstimateInBytes) * expectedOperationCount; int maxServerRequestOperationCount = Integer.MAX_VALUE; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequestTests. getBatchWithCreateOperationsAsync(operationCount, maxServerRequestBodyLength, maxServerRequestOperationCount, docSizeInBytes); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(expectedOperationCount); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()). isEqualTo(operationCount - serverOperationBatchRequest.getBatchRequest().getOperations().size()); } private static void verifyServerRequestCreationsByCountAsync( int expectedOperationCount, int operationCount, int docSizeInBytes) { int maxServerRequestBodyLength = Integer.MAX_VALUE; ServerOperationBatchRequest serverOperationBatchRequest = PartitionKeyRangeServerBatchRequestTests. getBatchWithCreateOperationsAsync(operationCount, maxServerRequestBodyLength, expectedOperationCount, docSizeInBytes); assertThat(serverOperationBatchRequest.getBatchRequest().getOperations().size()).isEqualTo(expectedOperationCount); assertThat(serverOperationBatchRequest.getBatchPendingOperations().size()). isEqualTo(operationCount - serverOperationBatchRequest.getBatchRequest().getOperations().size()); } private static ServerOperationBatchRequest getBatchWithCreateOperationsAsync( int operationCount, int maxServerRequestBodyLength, int maxServerRequestOperationCount, int docSizeInBytes) { List<CosmosItemOperation> operations = new ArrayList<>(); for (int i = 0; i < operationCount; i++) { JsonSerializable jsonSerializable = new JsonSerializable(); jsonSerializable.set("abc", StringUtils.repeat("x", docSizeInBytes - 10)); ItemBulkOperation<?> operation = new ItemBulkOperation<>( CosmosItemOperationType.CREATE, "", null, null, jsonSerializable ); operations.add(operation); } return PartitionKeyRangeServerBatchRequest.createBatchRequest( "0", operations, maxServerRequestBodyLength, maxServerRequestOperationCount); } }
use BoundingBox.toString()
public void recognizeContent() throws IOException { File form = new File("local/file_path/filename.png"); byte[] fileContent = Files.readAllBytes(form.toPath()); InputStream inputStream = new ByteArrayInputStream(fileContent); SyncPoller<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller = formRecognizerClient.beginRecognizeContent(inputStream, form.length()); List<FormPage> contentPageResults = recognizeContentPoller.getFinalResult(); for (int i = 0; i < contentPageResults.size(); i++) { FormPage formPage = contentPageResults.get(i); System.out.printf("----Recognizing content info for page %d ----%n", i); System.out.printf("Has width: %f and height: %f, measured with unit: %s.%n", formPage.getWidth(), formPage.getHeight(), formPage.getUnit()); formPage.getTables().forEach(formTable -> { System.out.printf("Table has %d rows and %d columns.%n", formTable.getRowCount(), formTable.getColumnCount()); formTable.getCells().forEach(formTableCell -> System.out.printf("Cell has text %s.%n", formTableCell.getText())); }); formPage.getSelectionMarks().forEach(selectionMark -> { StringBuilder boundingBoxStr = new StringBuilder(); selectionMark.getBoundingBox().getPoints().forEach( point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a confidence score %.2f.%n", selectionMark.getPageNumber(), selectionMark.getState(), boundingBoxStr, selectionMark.getConfidence()); }); } }
point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY())));
public void recognizeContent() throws IOException { File form = new File("local/file_path/filename.png"); byte[] fileContent = Files.readAllBytes(form.toPath()); InputStream inputStream = new ByteArrayInputStream(fileContent); SyncPoller<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller = formRecognizerClient.beginRecognizeContent(inputStream, form.length()); List<FormPage> contentPageResults = recognizeContentPoller.getFinalResult(); for (int i = 0; i < contentPageResults.size(); i++) { FormPage formPage = contentPageResults.get(i); System.out.printf("----Recognizing content info for page %d ----%n", i); System.out.printf("Has width: %f and height: %f, measured with unit: %s.%n", formPage.getWidth(), formPage.getHeight(), formPage.getUnit()); formPage.getTables().forEach(formTable -> { System.out.printf("Table has %d rows and %d columns.%n", formTable.getRowCount(), formTable.getColumnCount()); formTable.getCells().forEach(formTableCell -> System.out.printf("Cell has text %s.%n", formTableCell.getText())); }); formPage.getSelectionMarks().forEach(selectionMark -> System.out.printf( "Page: %s, Selection mark is %s within bounding box %s has a confidence score %.2f.%n", selectionMark.getPageNumber(), selectionMark.getState(), selectionMark.getBoundingBox().toString(), selectionMark.getConfidence())); } }
class ReadmeSamples { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); private FormTrainingClient formTrainingClient = new FormTrainingClientBuilder().buildClient(); /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting sync FormTraining client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialFormTrainingClient() { FormTrainingClient formTrainingClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } /** * Code snippet for getting async client using AAD authentication. */ public void useAadAsyncClient() { TokenCredential credential = new DefaultAzureCredentialBuilder().build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .endpoint("{endpoint}") .credential(credential) .buildClient(); } public void recognizeCustomForm() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller = formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl); List<RecognizedForm> recognizedForms = recognizeFormPoller.getFinalResult(); for (int i = 0; i < recognizedForms.size(); i++) { RecognizedForm form = recognizedForms.get(i); System.out.printf("----------- Recognized custom form info for page %d -----------%n", i); System.out.printf("Form type: %s%n", form.getFormType()); System.out.printf("Form type confidence: %.2f%n", form.getFormTypeConfidence()); form.getFields().forEach((label, formField) -> System.out.printf("Field %s has value %s with confidence score of %f.%n", label, formField.getValueData().getText(), formField.getConfidence()) ); } } /** * Recognize content/layout data for provided form. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void recognizeReceiptFromUrl() { String receiptUrl = "https: + "/contoso-allinone.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl); List<RecognizedForm> receiptPageResults = syncPoller.getFinalResult(); for (int i = 0; i < receiptPageResults.size(); i++) { RecognizedForm recognizedForm = receiptPageResults.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognizing receipt info for page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } } public void recognizeBusinessCardFromUrl() { String businessCardUrl = "https: + "/azure-ai-formrecognizer/src/samples/java/sample-forms/businessCards/businessCard.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> analyzeBusinessCardPoller = formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl); List<RecognizedForm> businessCardPageResults = analyzeBusinessCardPoller.getFinalResult(); for (int i = 0; i < businessCardPageResults.size(); i++) { RecognizedForm recognizedForm = businessCardPageResults.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized business card info for page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } } public void trainModel() { String trainingFilesUrl = "{SAS_URL_of_your_container_in_blob_storage}"; SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = formTrainingClient.beginTraining(trainingFilesUrl, false, new TrainingOptions() .setModelName("my model trained without labels"), Context.NONE); CustomFormModel customFormModel = trainingPoller.getFinalResult(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model name given by user: %s%n", customFormModel.getModelName()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); System.out.printf("Training started on: %s%n", customFormModel.getTrainingStartedOn()); System.out.printf("Training completed on: %s%n%n", customFormModel.getTrainingCompletedOn()); System.out.println("Recognized Fields:"); customFormModel.getSubmodels().forEach(customFormSubmodel -> { System.out.printf("Submodel Id: %s%n: ", customFormSubmodel.getModelId()); customFormSubmodel.getFields().forEach((field, customFormModelField) -> System.out.printf("Field: %s Field Label: %s%n", field, customFormModelField.getLabel())); }); } public void manageModels() { AccountProperties accountProperties = formTrainingClient.getAccountProperties(); System.out.printf("The account has %d custom models, and we can have at most %d custom models", accountProperties.getCustomModelCount(), accountProperties.getCustomModelLimit()); PagedIterable<CustomFormModelInfo> customModels = formTrainingClient.listCustomModels(); System.out.println("We have following models in the account:"); customModels.forEach(customFormModelInfo -> { System.out.printf("Model Id: %s%n", customFormModelInfo.getModelId()); CustomFormModel customModel = formTrainingClient.getCustomModel(customFormModelInfo.getModelId()); System.out.printf("Model Status: %s%n", customModel.getModelStatus()); System.out.printf("Training started on: %s%n", customModel.getTrainingStartedOn()); System.out.printf("Training completed on: %s%n", customModel.getTrainingCompletedOn()); customModel.getSubmodels().forEach(customFormSubmodel -> { System.out.printf("Custom Model Form type: %s%n", customFormSubmodel.getFormType()); System.out.printf("Custom Model Accuracy: %f%n", customFormSubmodel.getAccuracy()); if (customFormSubmodel.getFields() != null) { customFormSubmodel.getFields().forEach((fieldText, customFormModelField) -> { System.out.printf("Field Text: %s%n", fieldText); System.out.printf("Field Accuracy: %f%n", customFormModelField.getAccuracy()); }); } }); }); formTrainingClient.deleteModel("{modelId}"); } /** * Code snippet for handling exception */ public void handlingException() { try { formRecognizerClient.beginRecognizeContentFromUrl("invalidSourceUrl"); } catch (HttpResponseException e) { System.out.println(e.getMessage()); } } /** * Code snippet for getting async client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } }
class ReadmeSamples { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); private FormTrainingClient formTrainingClient = new FormTrainingClientBuilder().buildClient(); /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting sync FormTraining client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialFormTrainingClient() { FormTrainingClient formTrainingClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } /** * Code snippet for getting async client using AAD authentication. */ public void useAadAsyncClient() { TokenCredential credential = new DefaultAzureCredentialBuilder().build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .endpoint("{endpoint}") .credential(credential) .buildClient(); } public void recognizeCustomForm() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller = formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl); List<RecognizedForm> recognizedForms = recognizeFormPoller.getFinalResult(); for (int i = 0; i < recognizedForms.size(); i++) { RecognizedForm form = recognizedForms.get(i); System.out.printf("----------- Recognized custom form info for page %d -----------%n", i); System.out.printf("Form type: %s%n", form.getFormType()); System.out.printf("Form type confidence: %.2f%n", form.getFormTypeConfidence()); form.getFields().forEach((label, formField) -> System.out.printf("Field %s has value %s with confidence score of %f.%n", label, formField.getValueData().getText(), formField.getConfidence()) ); } } /** * Recognize content/layout data for provided form. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void recognizeReceiptFromUrl() { String receiptUrl = "https: + "/contoso-allinone.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl); List<RecognizedForm> receiptPageResults = syncPoller.getFinalResult(); for (int i = 0; i < receiptPageResults.size(); i++) { RecognizedForm recognizedForm = receiptPageResults.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognizing receipt info for page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } } public void recognizeBusinessCardFromUrl() { String businessCardUrl = "https: + "/azure-ai-formrecognizer/src/samples/java/sample-forms/businessCards/businessCard.jpg"; SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> analyzeBusinessCardPoller = formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl); List<RecognizedForm> businessCardPageResults = analyzeBusinessCardPoller.getFinalResult(); for (int i = 0; i < businessCardPageResults.size(); i++) { RecognizedForm recognizedForm = businessCardPageResults.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized business card info for page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } } public void trainModel() { String trainingFilesUrl = "{SAS_URL_of_your_container_in_blob_storage}"; SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = formTrainingClient.beginTraining(trainingFilesUrl, false, new TrainingOptions() .setModelName("my model trained without labels"), Context.NONE); CustomFormModel customFormModel = trainingPoller.getFinalResult(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model name given by user: %s%n", customFormModel.getModelName()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); System.out.printf("Training started on: %s%n", customFormModel.getTrainingStartedOn()); System.out.printf("Training completed on: %s%n%n", customFormModel.getTrainingCompletedOn()); System.out.println("Recognized Fields:"); customFormModel.getSubmodels().forEach(customFormSubmodel -> { System.out.printf("Submodel Id: %s%n: ", customFormSubmodel.getModelId()); customFormSubmodel.getFields().forEach((field, customFormModelField) -> System.out.printf("Field: %s Field Label: %s%n", field, customFormModelField.getLabel())); }); } public void manageModels() { AccountProperties accountProperties = formTrainingClient.getAccountProperties(); System.out.printf("The account has %d custom models, and we can have at most %d custom models", accountProperties.getCustomModelCount(), accountProperties.getCustomModelLimit()); PagedIterable<CustomFormModelInfo> customModels = formTrainingClient.listCustomModels(); System.out.println("We have following models in the account:"); customModels.forEach(customFormModelInfo -> { System.out.printf("Model Id: %s%n", customFormModelInfo.getModelId()); CustomFormModel customModel = formTrainingClient.getCustomModel(customFormModelInfo.getModelId()); System.out.printf("Model Status: %s%n", customModel.getModelStatus()); System.out.printf("Training started on: %s%n", customModel.getTrainingStartedOn()); System.out.printf("Training completed on: %s%n", customModel.getTrainingCompletedOn()); customModel.getSubmodels().forEach(customFormSubmodel -> { System.out.printf("Custom Model Form type: %s%n", customFormSubmodel.getFormType()); System.out.printf("Custom Model Accuracy: %f%n", customFormSubmodel.getAccuracy()); if (customFormSubmodel.getFields() != null) { customFormSubmodel.getFields().forEach((fieldText, customFormModelField) -> { System.out.printf("Field Text: %s%n", fieldText); System.out.printf("Field Accuracy: %f%n", customFormModelField.getAccuracy()); }); } }); }); formTrainingClient.deleteModel("{modelId}"); } /** * Code snippet for handling exception */ public void handlingException() { try { formRecognizerClient.beginRecognizeContentFromUrl("invalidSourceUrl"); } catch (HttpResponseException e) { System.out.println(e.getMessage()); } } /** * Code snippet for getting async client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } }
Let's keep the env vars out and samples consistent. Could think about this update for all or none in upcoming PR's/
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_FORM_RECOGNIZER_API_KEY"))) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_FORM_RECOGNIZER_ENDPOINT")) .buildClient(); File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/" + "forms/selectionMarkForm.pdf"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller = client.beginRecognizeContent(targetStream, sourceFile.length()); List<FormPage> contentPageResults = recognizeContentPoller.getFinalResult(); for (int i = 0; i < contentPageResults.size(); i++) { final FormPage formPage = contentPageResults.get(i); System.out.printf("---- Recognized content info for page %d ----%n", i); System.out.printf("Has width: %.2f and height: %.2f, measured with unit: %s%n", formPage.getWidth(), formPage.getHeight(), formPage.getUnit()); final List<FormTable> tables = formPage.getTables(); for (int i1 = 0; i1 < tables.size(); i1++) { final FormTable formTable = tables.get(i1); System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(), formTable.getColumnCount()); formTable.getCells().forEach(formTableCell -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formTableCell.getBoundingBox() != null) { formTableCell.getBoundingBox().getPoints().forEach( point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(), boundingBoxStr); }); System.out.println(); } final List<FormSelectionMark> selectionMarks = formPage.getSelectionMarks(); if (selectionMarks != null) { for (int j = 0; j < selectionMarks.size(); j++) { final FormSelectionMark selectionMark = selectionMarks.get(j); final StringBuilder boundingBoxStr = new StringBuilder(); selectionMark.getBoundingBox().getPoints().forEach( point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); System.out.printf( "Page: %s, Selection mark is %s within bounding box %s has a confidence score %.2f.%n", selectionMark.getPageNumber(), selectionMark.getState(), boundingBoxStr, selectionMark.getConfidence()); } } } }
.buildClient();
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/" + "forms/selectionMarkForm.pdf"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller = client.beginRecognizeContent(targetStream, sourceFile.length()); List<FormPage> contentPageResults = recognizeContentPoller.getFinalResult(); for (int i = 0; i < contentPageResults.size(); i++) { final FormPage formPage = contentPageResults.get(i); System.out.printf("---- Recognized content info for page %d ----%n", i); System.out.printf("Has width: %.2f and height: %.2f, measured with unit: %s%n", formPage.getWidth(), formPage.getHeight(), formPage.getUnit()); final List<FormTable> tables = formPage.getTables(); for (int i1 = 0; i1 < tables.size(); i1++) { final FormTable formTable = tables.get(i1); System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(), formTable.getColumnCount()); formTable.getCells().forEach(formTableCell -> System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(), formTableCell.getBoundingBox().toString())); System.out.println(); } for (FormSelectionMark selectionMark : formPage.getSelectionMarks()) { System.out.printf( "Page: %s, Selection mark is %s within bounding box %s has a confidence score %.2f.%n", selectionMark.getPageNumber(), selectionMark.getState(), selectionMark.getBoundingBox().toString(), selectionMark.getConfidence()); } } }
class RecognizeContentWithSelectionMarks { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
class RecognizeContentWithSelectionMarks { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
if recognize from url, shouldn't content-type be application/json?
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions() .setContentType(FormContentType.APPLICATION_PDF) .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageBusinessData(syncPoller.getFinalResult()); }, MULTIPAGE_BUSINESS_CARD_PDF); }
.setContentType(FormContentType.APPLICATION_PDF)
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageBusinessData(syncPoller.getFinalResult()); }, MULTIPAGE_BUSINESS_CARD_PDF); }
class FormRecognizerClientTest extends FormRecognizerClientTestBase { private FormRecognizerClient client; private FormRecognizerClient getFormRecognizerClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { return getFormRecognizerClientBuilder(httpClient, serviceVersion).buildClient(); } private FormTrainingClient getFormTrainingClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { return getFormTrainingClientBuilder(httpClient, serviceVersion).buildClient(); } /** * Verifies receipt data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeReceipts(null, 0)); } /** * Verifies content type will be auto detected when using receipt 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt 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 recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt data from a document using PNG file data as source and including text content details. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions().setContentType( FormContentType.IMAGE_PNG).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateBlankPdfResultData(syncPoller.getFinalResult()); }, BLANK_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE) .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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((sourceUrl) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions() .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((sourceUrl) -> assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode), Context.NONE))); } /** * Verifies receipt 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 recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt data for a document using source as PNG 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 recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_PNG); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(receiptUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl( receiptUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageReceiptData(syncPoller.getFinalResult()); }, MULTIPAGE_INVOICE_PDF); } /** * Verifies layout/content 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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) { client = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeContent(null, 0)); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent( getContentDetectionFileData(filePath), dataLength, new RecognizeContentOptions() .setContentType(null).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE) .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 recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions() .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions() .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateContentResultData(syncPoller.getFinalResult(), false); }, INVOICE_6_PDF); } /** * Verifies that an exception is thrown for invalid source url for recognizing content/layout information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> assertThrows( HttpResponseException.class, () -> client.beginRecognizeContentFromUrl(invalidSourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((formUrl) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateContentResultData(syncPoller.getFinalResult(), false); }, MULTIPAGE_INVOICE_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 recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), INVOICE_6_PDF); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 field elements. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, true); }), INVOICE_6_PDF); } /** * Verifies an exception thrown for a document using null form data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( syncPoller.getFinalResult().getModelId(), (InputStream) null, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( null, data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage()); }, INVOICE_6_PDF); } /** * Verifies an exception thrown for an empty model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( "", data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> { beginTrainingLabeledRunner((training, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(training, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class, () -> client.beginRecognizeCustomFormsFromUrl(createdModel.getModelId(), invalidSourceUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE).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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> beginTrainingLabeledRunner( (trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), getContentDetectionFileData(filePath), dataLength, new RecognizeCustomFormsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), INVOICE_6_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, true, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataLabeled(syncPoller.getFinalResult()); }), MULTIPAGE_INVOICE_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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 element references */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, false); }), INVOICE_6_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, false, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, false); }), FORM_JPG); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlPdfUnlabeledRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, false, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataUnlabeled(syncPoller.getFinalResult()); })); } /** * Verifies that an exception is thrown for invalid training data source. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); HttpResponseException httpResponseException = assertThrows( HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl( createdModel.getModelId(), INVALID_URL, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE).getFinalResult()); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomFormsFromUrl( null, fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage()); }, FORM_JPG); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> client.beginRecognizeCustomFormsFromUrl("", fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage()); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), FORM_JPG); } /** * 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) { urlRunner(fileUrl -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, true, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataLabeled(syncPoller.getFinalResult()); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, sourceUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE)); validateExceptionSource(errorResponseException); }); } /** * Verify that custom forom with invalid model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUrlNonExistModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); FormRecognizerException errorResponseException = assertThrows(FormRecognizerException.class, () -> client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE).getFinalResult()); assertEquals(UNABLE_TO_READ_FILE_ERROR_CODE, errorResponseException.getErrorInformation().get(0).getErrorCode()); })); } /** * Verifies recognized form type when labeled model used for recognition and model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeLabeledWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("custom:model1", recognizedForm.getFormType()); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("custom:model1", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when labeled model used for recognition and model name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeLabeledModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("custom:" + createdModel.getModelId(), recognizedForm.getFormType()); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("custom:" + createdModel.getModelId(), submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when unlabeled model used for recognition and model name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeUnlabeledModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("form-0", recognizedForm.getFormType()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("form-0", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when unlabeled model used for recognition and model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeUnlabeledModelWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("form-0", recognizedForm.getFormType()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("form-0", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when using composed model for recognition when display name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeComposedModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller1 = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); CustomFormModel createdModel1 = syncPoller1.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller2 = formTrainingClient.beginCreateComposedModel( Arrays.asList(createdModel.getModelId(), createdModel1.getModelId()), new CreateComposedModelOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller2.waitForCompletion(); CustomFormModel composedModel = syncPoller2.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller3 = formRecognizerClient.beginRecognizeCustomForms( composedModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller3.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller3.getFinalResult().stream().findFirst().get(); assertTrue("custom:".equals(recognizedForm.getFormType())); assertNotNull(recognizedForm.getFormTypeConfidence()); composedModel.getSubmodels() .forEach(customFormSubmodel -> { if (createdModel.getModelId().equals(customFormSubmodel.getModelId())) { assertEquals("custom:" + createdModel.getModelId(), customFormSubmodel.getFormType()); } else { assertEquals("custom:" + createdModel1.getModelId(), customFormSubmodel.getFormType()); } }); formTrainingClient.deleteModel(createdModel.getModelId()); formTrainingClient.deleteModel(createdModel1.getModelId()); formTrainingClient.deleteModel(composedModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when using composed model for recognition when model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeComposedModelWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller1 = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model2"), Context.NONE); syncPoller1.waitForCompletion(); CustomFormModel createdModel1 = syncPoller1.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller2 = formTrainingClient.beginCreateComposedModel( Arrays.asList(createdModel.getModelId(), createdModel1.getModelId()), new CreateComposedModelOptions().setPollInterval(durationTestMode) .setModelName("composedModelName"), Context.NONE); syncPoller2.waitForCompletion(); CustomFormModel composedModel = syncPoller2.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller3 = formRecognizerClient.beginRecognizeCustomForms( composedModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller3.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller3.getFinalResult().stream().findFirst().get(); String expectedFormType1 = "composedModelName:model1"; String expectedFormType2 = "composedModelName:model2"; assertTrue(expectedFormType1.equals(recognizedForm.getFormType()) || expectedFormType2.equals(recognizedForm.getFormType())); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = composedModel.getSubmodels().get(0); assertEquals("custom:" + createdModel.getModelId(), submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); formTrainingClient.deleteModel(createdModel1.getModelId()); formTrainingClient.deleteModel(composedModel.getModelId()); }); }, FORM_JPG); } /** * Verifies business card data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeBusinessCards( null, 0)); } /** * Verifies content type will be auto detected when using business card 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(getContentDetectionFileData(filePath), dataLength, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD); }, BUSINESS_CARD_JPG); } /** * Verifies business card 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 recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); 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 text content details. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType( FormContentType.IMAGE_PNG).setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE) .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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions() .setContentType(FormContentType.APPLICATION_PDF) .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((sourceUrl) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((sourceUrl) -> assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE))); } /** * Verifies business card 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 recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 form 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 /* * Verify unsupported locales throws when an invalid locale supplied */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void invalidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions().setPollInterval(durationTestMode).setLocale("random"), Context.NONE)); assertEquals("UnsupportedLocale", ((FormRecognizerErrorInformation) httpResponseException.getValue()).getErrorCode()); }, RECEIPT_CONTOSO_JPG); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions().setPollInterval(durationTestMode).setLocale("en-US"), Context.NONE); validateNetworkCallRecord("locale", "en-US"); }, RECEIPT_CONTOSO_JPG); } }
class FormRecognizerClientTest extends FormRecognizerClientTestBase { private FormRecognizerClient client; private FormRecognizerClient getFormRecognizerClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { return getFormRecognizerClientBuilder(httpClient, serviceVersion).buildClient(); } private FormTrainingClient getFormTrainingClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { return getFormTrainingClientBuilder(httpClient, serviceVersion).buildClient(); } /** * Verifies receipt data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeReceipts(null, 0)); } /** * Verifies content type will be auto detected when using receipt 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt 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 recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt data from a document using PNG file data as source and including text content details. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions().setContentType( FormContentType.IMAGE_PNG).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateBlankPdfResultData(syncPoller.getFinalResult()); }, BLANK_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE) .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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((sourceUrl) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions() .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((sourceUrl) -> assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode), Context.NONE))); } /** * Verifies receipt 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 recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt data for a document using source as PNG 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 recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_PNG); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(receiptUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl( receiptUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageReceiptData(syncPoller.getFinalResult()); }, MULTIPAGE_INVOICE_PDF); } /** * Verifies layout/content 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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) { client = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeContent(null, 0)); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent( getContentDetectionFileData(filePath), dataLength, new RecognizeContentOptions() .setContentType(null).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE) .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 recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions() .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions() .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateContentResultData(syncPoller.getFinalResult(), false); }, INVOICE_6_PDF); } /** * Verifies that an exception is thrown for invalid source url for recognizing content/layout information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> assertThrows( HttpResponseException.class, () -> client.beginRecognizeContentFromUrl(invalidSourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((formUrl) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateContentResultData(syncPoller.getFinalResult(), false); }, MULTIPAGE_INVOICE_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 recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), INVOICE_6_PDF); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 field elements. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, true); }), INVOICE_6_PDF); } /** * Verifies an exception thrown for a document using null form data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( syncPoller.getFinalResult().getModelId(), (InputStream) null, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( null, data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage()); }, INVOICE_6_PDF); } /** * Verifies an exception thrown for an empty model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( "", data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> { beginTrainingLabeledRunner((training, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(training, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class, () -> client.beginRecognizeCustomFormsFromUrl(createdModel.getModelId(), invalidSourceUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE).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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> beginTrainingLabeledRunner( (trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), getContentDetectionFileData(filePath), dataLength, new RecognizeCustomFormsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), INVOICE_6_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, true, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataLabeled(syncPoller.getFinalResult()); }), MULTIPAGE_INVOICE_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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 element references */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, false); }), INVOICE_6_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, false, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, false); }), FORM_JPG); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlPdfUnlabeledRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, false, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataUnlabeled(syncPoller.getFinalResult()); })); } /** * Verifies that an exception is thrown for invalid training data source. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); HttpResponseException httpResponseException = assertThrows( HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl( createdModel.getModelId(), INVALID_URL, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE).getFinalResult()); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomFormsFromUrl( null, fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage()); }, FORM_JPG); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> client.beginRecognizeCustomFormsFromUrl("", fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage()); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), FORM_JPG); } /** * 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) { urlRunner(fileUrl -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, true, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataLabeled(syncPoller.getFinalResult()); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, sourceUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE)); validateExceptionSource(errorResponseException); }); } /** * Verify that custom forom with invalid model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUrlNonExistModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); FormRecognizerException errorResponseException = assertThrows(FormRecognizerException.class, () -> client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE).getFinalResult()); assertEquals(UNABLE_TO_READ_FILE_ERROR_CODE, errorResponseException.getErrorInformation().get(0).getErrorCode()); })); } /** * Verifies recognized form type when labeled model used for recognition and model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeLabeledWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("custom:model1", recognizedForm.getFormType()); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("custom:model1", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when labeled model used for recognition and model name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeLabeledModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("custom:" + createdModel.getModelId(), recognizedForm.getFormType()); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("custom:" + createdModel.getModelId(), submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when unlabeled model used for recognition and model name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeUnlabeledModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("form-0", recognizedForm.getFormType()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("form-0", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when unlabeled model used for recognition and model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeUnlabeledModelWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("form-0", recognizedForm.getFormType()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("form-0", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when using composed model for recognition when display name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeComposedModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller1 = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); CustomFormModel createdModel1 = syncPoller1.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller2 = formTrainingClient.beginCreateComposedModel( Arrays.asList(createdModel.getModelId(), createdModel1.getModelId()), new CreateComposedModelOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller2.waitForCompletion(); CustomFormModel composedModel = syncPoller2.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller3 = formRecognizerClient.beginRecognizeCustomForms( composedModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller3.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller3.getFinalResult().stream().findFirst().get(); assertTrue("custom:".equals(recognizedForm.getFormType())); assertNotNull(recognizedForm.getFormTypeConfidence()); composedModel.getSubmodels() .forEach(customFormSubmodel -> { if (createdModel.getModelId().equals(customFormSubmodel.getModelId())) { assertEquals("custom:" + createdModel.getModelId(), customFormSubmodel.getFormType()); } else { assertEquals("custom:" + createdModel1.getModelId(), customFormSubmodel.getFormType()); } }); formTrainingClient.deleteModel(createdModel.getModelId()); formTrainingClient.deleteModel(createdModel1.getModelId()); formTrainingClient.deleteModel(composedModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when using composed model for recognition when model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeComposedModelWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller1 = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model2"), Context.NONE); syncPoller1.waitForCompletion(); CustomFormModel createdModel1 = syncPoller1.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller2 = formTrainingClient.beginCreateComposedModel( Arrays.asList(createdModel.getModelId(), createdModel1.getModelId()), new CreateComposedModelOptions().setPollInterval(durationTestMode) .setModelName("composedModelName"), Context.NONE); syncPoller2.waitForCompletion(); CustomFormModel composedModel = syncPoller2.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller3 = formRecognizerClient.beginRecognizeCustomForms( composedModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller3.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller3.getFinalResult().stream().findFirst().get(); String expectedFormType1 = "composedModelName:model1"; String expectedFormType2 = "composedModelName:model2"; assertTrue(expectedFormType1.equals(recognizedForm.getFormType()) || expectedFormType2.equals(recognizedForm.getFormType())); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = composedModel.getSubmodels().get(0); assertEquals("custom:" + createdModel.getModelId(), submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); formTrainingClient.deleteModel(createdModel1.getModelId()); formTrainingClient.deleteModel(composedModel.getModelId()); }); }, FORM_JPG); } /** * Verifies business card data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeBusinessCards( null, 0)); } /** * Verifies content type will be auto detected when using business card 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(getContentDetectionFileData(filePath), dataLength, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD); }, BUSINESS_CARD_JPG); } /** * Verifies business card 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 recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); 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 text content details. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType( FormContentType.IMAGE_PNG).setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE) .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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions() .setContentType(FormContentType.APPLICATION_PDF) .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((sourceUrl) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((sourceUrl) -> assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE))); } /** * Verifies business card 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 recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 form 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 /* * Verify unsupported locales throws when an invalid locale supplied */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void invalidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions().setPollInterval(durationTestMode).setLocale("random"), Context.NONE)); assertEquals("UnsupportedLocale", ((FormRecognizerErrorInformation) httpResponseException.getValue()).getErrorCode()); }, RECEIPT_CONTOSO_JPG); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions().setPollInterval(durationTestMode).setLocale("en-US"), Context.NONE); validateNetworkCallRecord("locale", "en-US"); }, RECEIPT_CONTOSO_JPG); } }
yes, this value is ignored, will update!
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions() .setContentType(FormContentType.APPLICATION_PDF) .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageBusinessData(syncPoller.getFinalResult()); }, MULTIPAGE_BUSINESS_CARD_PDF); }
.setContentType(FormContentType.APPLICATION_PDF)
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageBusinessData(syncPoller.getFinalResult()); }, MULTIPAGE_BUSINESS_CARD_PDF); }
class FormRecognizerClientTest extends FormRecognizerClientTestBase { private FormRecognizerClient client; private FormRecognizerClient getFormRecognizerClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { return getFormRecognizerClientBuilder(httpClient, serviceVersion).buildClient(); } private FormTrainingClient getFormTrainingClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { return getFormTrainingClientBuilder(httpClient, serviceVersion).buildClient(); } /** * Verifies receipt data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeReceipts(null, 0)); } /** * Verifies content type will be auto detected when using receipt 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt 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 recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt data from a document using PNG file data as source and including text content details. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions().setContentType( FormContentType.IMAGE_PNG).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateBlankPdfResultData(syncPoller.getFinalResult()); }, BLANK_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE) .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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((sourceUrl) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions() .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((sourceUrl) -> assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode), Context.NONE))); } /** * Verifies receipt 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 recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt data for a document using source as PNG 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 recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_PNG); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(receiptUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl( receiptUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageReceiptData(syncPoller.getFinalResult()); }, MULTIPAGE_INVOICE_PDF); } /** * Verifies layout/content 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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) { client = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeContent(null, 0)); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent( getContentDetectionFileData(filePath), dataLength, new RecognizeContentOptions() .setContentType(null).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE) .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 recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions() .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions() .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateContentResultData(syncPoller.getFinalResult(), false); }, INVOICE_6_PDF); } /** * Verifies that an exception is thrown for invalid source url for recognizing content/layout information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> assertThrows( HttpResponseException.class, () -> client.beginRecognizeContentFromUrl(invalidSourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((formUrl) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateContentResultData(syncPoller.getFinalResult(), false); }, MULTIPAGE_INVOICE_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 recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), INVOICE_6_PDF); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 field elements. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, true); }), INVOICE_6_PDF); } /** * Verifies an exception thrown for a document using null form data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( syncPoller.getFinalResult().getModelId(), (InputStream) null, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( null, data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage()); }, INVOICE_6_PDF); } /** * Verifies an exception thrown for an empty model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( "", data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> { beginTrainingLabeledRunner((training, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(training, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class, () -> client.beginRecognizeCustomFormsFromUrl(createdModel.getModelId(), invalidSourceUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE).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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> beginTrainingLabeledRunner( (trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), getContentDetectionFileData(filePath), dataLength, new RecognizeCustomFormsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), INVOICE_6_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, true, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataLabeled(syncPoller.getFinalResult()); }), MULTIPAGE_INVOICE_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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 element references */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, false); }), INVOICE_6_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, false, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, false); }), FORM_JPG); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlPdfUnlabeledRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, false, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataUnlabeled(syncPoller.getFinalResult()); })); } /** * Verifies that an exception is thrown for invalid training data source. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); HttpResponseException httpResponseException = assertThrows( HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl( createdModel.getModelId(), INVALID_URL, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE).getFinalResult()); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomFormsFromUrl( null, fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage()); }, FORM_JPG); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> client.beginRecognizeCustomFormsFromUrl("", fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage()); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), FORM_JPG); } /** * 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) { urlRunner(fileUrl -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, true, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataLabeled(syncPoller.getFinalResult()); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, sourceUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE)); validateExceptionSource(errorResponseException); }); } /** * Verify that custom forom with invalid model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUrlNonExistModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); FormRecognizerException errorResponseException = assertThrows(FormRecognizerException.class, () -> client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE).getFinalResult()); assertEquals(UNABLE_TO_READ_FILE_ERROR_CODE, errorResponseException.getErrorInformation().get(0).getErrorCode()); })); } /** * Verifies recognized form type when labeled model used for recognition and model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeLabeledWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("custom:model1", recognizedForm.getFormType()); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("custom:model1", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when labeled model used for recognition and model name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeLabeledModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("custom:" + createdModel.getModelId(), recognizedForm.getFormType()); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("custom:" + createdModel.getModelId(), submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when unlabeled model used for recognition and model name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeUnlabeledModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("form-0", recognizedForm.getFormType()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("form-0", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when unlabeled model used for recognition and model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeUnlabeledModelWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("form-0", recognizedForm.getFormType()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("form-0", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when using composed model for recognition when display name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeComposedModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller1 = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); CustomFormModel createdModel1 = syncPoller1.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller2 = formTrainingClient.beginCreateComposedModel( Arrays.asList(createdModel.getModelId(), createdModel1.getModelId()), new CreateComposedModelOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller2.waitForCompletion(); CustomFormModel composedModel = syncPoller2.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller3 = formRecognizerClient.beginRecognizeCustomForms( composedModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller3.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller3.getFinalResult().stream().findFirst().get(); assertTrue("custom:".equals(recognizedForm.getFormType())); assertNotNull(recognizedForm.getFormTypeConfidence()); composedModel.getSubmodels() .forEach(customFormSubmodel -> { if (createdModel.getModelId().equals(customFormSubmodel.getModelId())) { assertEquals("custom:" + createdModel.getModelId(), customFormSubmodel.getFormType()); } else { assertEquals("custom:" + createdModel1.getModelId(), customFormSubmodel.getFormType()); } }); formTrainingClient.deleteModel(createdModel.getModelId()); formTrainingClient.deleteModel(createdModel1.getModelId()); formTrainingClient.deleteModel(composedModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when using composed model for recognition when model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeComposedModelWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller1 = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model2"), Context.NONE); syncPoller1.waitForCompletion(); CustomFormModel createdModel1 = syncPoller1.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller2 = formTrainingClient.beginCreateComposedModel( Arrays.asList(createdModel.getModelId(), createdModel1.getModelId()), new CreateComposedModelOptions().setPollInterval(durationTestMode) .setModelName("composedModelName"), Context.NONE); syncPoller2.waitForCompletion(); CustomFormModel composedModel = syncPoller2.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller3 = formRecognizerClient.beginRecognizeCustomForms( composedModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller3.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller3.getFinalResult().stream().findFirst().get(); String expectedFormType1 = "composedModelName:model1"; String expectedFormType2 = "composedModelName:model2"; assertTrue(expectedFormType1.equals(recognizedForm.getFormType()) || expectedFormType2.equals(recognizedForm.getFormType())); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = composedModel.getSubmodels().get(0); assertEquals("custom:" + createdModel.getModelId(), submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); formTrainingClient.deleteModel(createdModel1.getModelId()); formTrainingClient.deleteModel(composedModel.getModelId()); }); }, FORM_JPG); } /** * Verifies business card data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeBusinessCards( null, 0)); } /** * Verifies content type will be auto detected when using business card 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(getContentDetectionFileData(filePath), dataLength, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD); }, BUSINESS_CARD_JPG); } /** * Verifies business card 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 recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); 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 text content details. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType( FormContentType.IMAGE_PNG).setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE) .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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions() .setContentType(FormContentType.APPLICATION_PDF) .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((sourceUrl) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((sourceUrl) -> assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE))); } /** * Verifies business card 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 recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 form 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 /* * Verify unsupported locales throws when an invalid locale supplied */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void invalidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions().setPollInterval(durationTestMode).setLocale("random"), Context.NONE)); assertEquals("UnsupportedLocale", ((FormRecognizerErrorInformation) httpResponseException.getValue()).getErrorCode()); }, RECEIPT_CONTOSO_JPG); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions().setPollInterval(durationTestMode).setLocale("en-US"), Context.NONE); validateNetworkCallRecord("locale", "en-US"); }, RECEIPT_CONTOSO_JPG); } }
class FormRecognizerClientTest extends FormRecognizerClientTestBase { private FormRecognizerClient client; private FormRecognizerClient getFormRecognizerClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { return getFormRecognizerClientBuilder(httpClient, serviceVersion).buildClient(); } private FormTrainingClient getFormTrainingClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { return getFormTrainingClientBuilder(httpClient, serviceVersion).buildClient(); } /** * Verifies receipt data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeReceipts(null, 0)); } /** * Verifies content type will be auto detected when using receipt 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), false, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt 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 recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt data from a document using PNG file data as source and including text content details. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions().setContentType( FormContentType.IMAGE_PNG).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateBlankPdfResultData(syncPoller.getFinalResult()); }, BLANK_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceipts( data, dataLength, new RecognizeReceiptsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceipts(data, dataLength, new RecognizeReceiptsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE) .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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((sourceUrl) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions() .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((sourceUrl) -> assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode), Context.NONE))); } /** * Verifies receipt 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 recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_JPG); } /** * Verifies receipt data for a document using source as PNG 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 recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, new RecognizeReceiptsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), true, RECEIPT); }, RECEIPT_CONTOSO_PNG); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(receiptUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeReceiptsFromUrl( receiptUrl, new RecognizeReceiptsOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageReceiptData(syncPoller.getFinalResult()); }, MULTIPAGE_INVOICE_PDF); } /** * Verifies layout/content 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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) { client = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeContent(null, 0)); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent( getContentDetectionFileData(filePath), dataLength, new RecognizeContentOptions() .setContentType(null).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeContent(data, dataLength, new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE) .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 recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions() .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions() .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateContentResultData(syncPoller.getFinalResult(), false); }, INVOICE_6_PDF); } /** * Verifies that an exception is thrown for invalid source url for recognizing content/layout information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> assertThrows( HttpResponseException.class, () -> client.beginRecognizeContentFromUrl(invalidSourceUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((formUrl) -> { SyncPoller<FormRecognizerOperationResult, List<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateContentResultData(syncPoller.getFinalResult(), false); }, MULTIPAGE_INVOICE_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 recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), INVOICE_6_PDF); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 field elements. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, true); }), INVOICE_6_PDF); } /** * Verifies an exception thrown for a document using null form data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( syncPoller.getFinalResult().getModelId(), (InputStream) null, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( null, data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage()); }, INVOICE_6_PDF); } /** * Verifies an exception thrown for an empty model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms( "", data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> { beginTrainingLabeledRunner((training, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(training, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class, () -> client.beginRecognizeCustomFormsFromUrl(createdModel.getModelId(), invalidSourceUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE).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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> beginTrainingLabeledRunner( (trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), getContentDetectionFileData(filePath), dataLength, new RecognizeCustomFormsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), INVOICE_6_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, true, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataLabeled(syncPoller.getFinalResult()); }), MULTIPAGE_INVOICE_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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 element references */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, false); }), INVOICE_6_PDF); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, false, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, false); }), FORM_JPG); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlPdfUnlabeledRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, false, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataUnlabeled(syncPoller.getFinalResult()); })); } /** * Verifies that an exception is thrown for invalid training data source. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); HttpResponseException httpResponseException = assertThrows( HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl( createdModel.getModelId(), INVALID_URL, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE).getFinalResult()); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> { Exception ex = assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomFormsFromUrl( null, fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); assertEquals(MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE, ex.getMessage()); }, FORM_JPG); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> client.beginRecognizeCustomFormsFromUrl("", fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); assertEquals(INVALID_UUID_EXCEPTION_MESSAGE, ex.getMessage()); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }), FORM_JPG); } /** * 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) { urlRunner(fileUrl -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> beginTrainingMultipageRunner((trainingFilesUrl) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, true, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomFormsFromUrl( trainingPoller.getFinalResult().getModelId(), fileUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultiPageDataLabeled(syncPoller.getFinalResult()); }), 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, sourceUrl, new RecognizeCustomFormsOptions() .setPollInterval(durationTestMode), Context.NONE)); validateExceptionSource(errorResponseException); }); } /** * Verify that custom forom with invalid model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUrlNonExistModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(fileUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(NON_EXIST_MODEL_ID, fileUrl, new RecognizeCustomFormsOptions().setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = getFormTrainingClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); trainingPoller.waitForCompletion(); FormRecognizerException errorResponseException = assertThrows(FormRecognizerException.class, () -> client.beginRecognizeCustomForms(trainingPoller.getFinalResult().getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.APPLICATION_PDF).setPollInterval(durationTestMode), Context.NONE).getFinalResult()); assertEquals(UNABLE_TO_READ_FILE_ERROR_CODE, errorResponseException.getErrorInformation().get(0).getErrorCode()); })); } /** * Verifies recognized form type when labeled model used for recognition and model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeLabeledWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("custom:model1", recognizedForm.getFormType()); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("custom:model1", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when labeled model used for recognition and model name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeLabeledModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("custom:" + createdModel.getModelId(), recognizedForm.getFormType()); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("custom:" + createdModel.getModelId(), submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when unlabeled model used for recognition and model name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeUnlabeledModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("form-0", recognizedForm.getFormType()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("form-0", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when unlabeled model used for recognition and model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizedFormTypeUnlabeledModelWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller1 = formRecognizerClient.beginRecognizeCustomForms( createdModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller1.getFinalResult().stream().findFirst().get(); assertEquals("form-0", recognizedForm.getFormType()); final CustomFormSubmodel submodel = createdModel.getSubmodels().get(0); assertEquals("form-0", submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when using composed model for recognition when display name is not provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeComposedModel( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller1 = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller1.waitForCompletion(); CustomFormModel createdModel1 = syncPoller1.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller2 = formTrainingClient.beginCreateComposedModel( Arrays.asList(createdModel.getModelId(), createdModel1.getModelId()), new CreateComposedModelOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller2.waitForCompletion(); CustomFormModel composedModel = syncPoller2.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller3 = formRecognizerClient.beginRecognizeCustomForms( composedModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller3.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller3.getFinalResult().stream().findFirst().get(); assertTrue("custom:".equals(recognizedForm.getFormType())); assertNotNull(recognizedForm.getFormTypeConfidence()); composedModel.getSubmodels() .forEach(customFormSubmodel -> { if (createdModel.getModelId().equals(customFormSubmodel.getModelId())) { assertEquals("custom:" + createdModel.getModelId(), customFormSubmodel.getFormType()); } else { assertEquals("custom:" + createdModel1.getModelId(), customFormSubmodel.getFormType()); } }); formTrainingClient.deleteModel(createdModel.getModelId()); formTrainingClient.deleteModel(createdModel1.getModelId()); formTrainingClient.deleteModel(composedModel.getModelId()); }); }, FORM_JPG); } /** * Verifies recognized form type when using composed model for recognition when model name is provided by user. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void checkRecognizeFormTypeComposedModelWithModelName( HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { final FormTrainingClient formTrainingClient = getFormTrainingClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model1"), Context.NONE); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller1 = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode).setModelName("model2"), Context.NONE); syncPoller1.waitForCompletion(); CustomFormModel createdModel1 = syncPoller1.getFinalResult(); SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller2 = formTrainingClient.beginCreateComposedModel( Arrays.asList(createdModel.getModelId(), createdModel1.getModelId()), new CreateComposedModelOptions().setPollInterval(durationTestMode) .setModelName("composedModelName"), Context.NONE); syncPoller2.waitForCompletion(); CustomFormModel composedModel = syncPoller2.getFinalResult(); FormRecognizerClient formRecognizerClient = getFormTrainingClient(httpClient, serviceVersion) .getFormRecognizerClient(); SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller3 = formRecognizerClient.beginRecognizeCustomForms( composedModel.getModelId(), data, dataLength, new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG).setPollInterval(durationTestMode), Context.NONE); syncPoller3.waitForCompletion(); final RecognizedForm recognizedForm = syncPoller3.getFinalResult().stream().findFirst().get(); String expectedFormType1 = "composedModelName:model1"; String expectedFormType2 = "composedModelName:model2"; assertTrue(expectedFormType1.equals(recognizedForm.getFormType()) || expectedFormType2.equals(recognizedForm.getFormType())); assertNotNull(recognizedForm.getFormTypeConfidence()); final CustomFormSubmodel submodel = composedModel.getSubmodels().get(0); assertEquals("custom:" + createdModel.getModelId(), submodel.getFormType()); formTrainingClient.deleteModel(createdModel.getModelId()); formTrainingClient.deleteModel(createdModel1.getModelId()); formTrainingClient.deleteModel(composedModel.getModelId()); }); }, FORM_JPG); } /** * Verifies business card data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(NullPointerException.class, () -> client.beginRecognizeBusinessCards( null, 0)); } /** * Verifies content type will be auto detected when using business card 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(getContentDetectionFileData(filePath), dataLength, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validatePrebuiltResultData(syncPoller.getFinalResult(), false, BUSINESS_CARD); }, BUSINESS_CARD_JPG); } /** * Verifies business card 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 recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); 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 text content details. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType( FormContentType.IMAGE_PNG).setFieldElementsIncluded(true).setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); damagedPdfDataRunner((data, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions().setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(durationTestMode), Context.NONE) .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 = getFormRecognizerClient(httpClient, serviceVersion); dataRunner((data, dataLength) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCards(data, dataLength, new RecognizeBusinessCardsOptions() .setContentType(FormContentType.APPLICATION_PDF) .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner((sourceUrl) -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl); 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 = getFormRecognizerClient(httpClient, serviceVersion); encodedBlankSpaceSourceUrlRunner(sourceUrl -> { HttpResponseException errorResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE)); 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 = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((sourceUrl) -> assertThrows(HttpResponseException.class, () -> client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setPollInterval(durationTestMode), Context.NONE))); } /** * Verifies business card 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 recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 form 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 = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions().setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); 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 /* * Verify unsupported locales throws when an invalid locale supplied */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void invalidLocale(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions().setPollInterval(durationTestMode).setLocale("random"), Context.NONE)); assertEquals("UnsupportedLocale", ((FormRecognizerErrorInformation) httpResponseException.getValue()).getErrorCode()); }, RECEIPT_CONTOSO_JPG); } /** * 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 = getFormRecognizerClient(httpClient, serviceVersion); localFilePathRunner((filePath, dataLength) -> { client.beginRecognizeReceipts( getContentDetectionFileData(filePath), dataLength, new RecognizeReceiptsOptions().setPollInterval(durationTestMode).setLocale("en-US"), Context.NONE); validateNetworkCallRecord("locale", "en-US"); }, RECEIPT_CONTOSO_JPG); } }
in a future PR, this will be a great place to check that the page for ContactName is `2`
static void validateMultipageBusinessData(List<RecognizedForm> recognizedBusinessCards) { assertEquals(2, recognizedBusinessCards.size()); RecognizedForm businessCard1 = recognizedBusinessCards.get(0); RecognizedForm businessCard2 = recognizedBusinessCards.get(1); assertEquals(1, businessCard1.getPageRange().getFirstPageNumber()); assertEquals(1, businessCard1.getPageRange().getLastPageNumber()); Map<String, FormField> businessCard1Fields = businessCard1.getFields(); List<FormField> emailList = businessCard1Fields.get("Emails").getValue().asList(); assertEquals("johnsinger@contoso.com", emailList.get(0).getValue().asString()); List<FormField> phoneNumberList = businessCard1Fields.get("OtherPhones").getValue().asList(); assertEquals("+14257793479", phoneNumberList.get(0).getValue().asPhoneNumber()); assertNotNull(businessCard1.getPages()); assertEquals(2, businessCard2.getPageRange().getFirstPageNumber()); assertEquals(2, businessCard2.getPageRange().getLastPageNumber()); Map<String, FormField> businessCard2Fields = businessCard2.getFields(); List<FormField> email2List = businessCard2Fields.get("Emails").getValue().asList(); assertEquals("avery.smith@contoso.com", email2List.get(0).getValue().asString()); List<FormField> phoneNumber2List = businessCard2Fields.get("OtherPhones").getValue().asList(); assertEquals("+44 (0) 20 9876 5432", phoneNumber2List.get(0).getValueData().getText()); assertNotNull(businessCard2.getPages()); }
Map<String, FormField> businessCard2Fields = businessCard2.getFields();
static void validateMultipageBusinessData(List<RecognizedForm> recognizedBusinessCards) { assertEquals(2, recognizedBusinessCards.size()); RecognizedForm businessCard1 = recognizedBusinessCards.get(0); RecognizedForm businessCard2 = recognizedBusinessCards.get(1); assertEquals(1, businessCard1.getPageRange().getFirstPageNumber()); assertEquals(1, businessCard1.getPageRange().getLastPageNumber()); Map<String, FormField> businessCard1Fields = businessCard1.getFields(); List<FormField> emailList = businessCard1Fields.get("Emails").getValue().asList(); assertEquals("johnsinger@contoso.com", emailList.get(0).getValue().asString()); List<FormField> phoneNumberList = businessCard1Fields.get("OtherPhones").getValue().asList(); assertEquals("+14257793479", phoneNumberList.get(0).getValue().asPhoneNumber()); assertNotNull(businessCard1.getPages()); assertEquals(2, businessCard2.getPageRange().getFirstPageNumber()); assertEquals(2, businessCard2.getPageRange().getLastPageNumber()); Map<String, FormField> businessCard2Fields = businessCard2.getFields(); List<FormField> email2List = businessCard2Fields.get("Emails").getValue().asList(); assertEquals("avery.smith@contoso.com", email2List.get(0).getValue().asString()); List<FormField> phoneNumber2List = businessCard2Fields.get("OtherPhones").getValue().asList(); assertEquals("+44 (0) 20 9876 5432", phoneNumber2List.get(0).getValueData().getText()); assertNotNull(businessCard2.getPages()); }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String MULTIPAGE_BUSINESS_CARD_PDF = "business-card-multipage.pdf"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final List<String> BUSINESS_CARD_FIELDS = Arrays.asList("ContactNames", "JobTitles", "Departments", "Emails", "Websites", "MobilePhones", "OtherPhones", "Faxes", "Addresses", "CompanyNames"); static final List<String> RECEIPT_FIELDS = Arrays.asList("MerchantName", "MerchantPhoneNumber", "MerchantAddress", "Total", "Subtotal", "Tax", "TransactionDate", "TransactionDate", "TransactionTime", "Items"); enum PREBUILT_TYPE { RECEIPT, BUSINESS_CARD } Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validatePrebuiltResultData(List<RecognizedForm> actualPrebuiltRecognizedForms, boolean includeFieldElements, PREBUILT_TYPE prebuiltType) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); final List<ReadResult> rawReadResults = rawResponse.getReadResults(); for (int i = 0; i < actualPrebuiltRecognizedForms.size(); i++) { final RecognizedForm actualForm = actualPrebuiltRecognizedForms.get(i); final DocumentResult rawDocumentResult = rawResponse.getDocumentResults().get(i); validateLabeledData(actualForm, includeFieldElements, rawReadResults, rawDocumentResult); if (BUSINESS_CARD.equals(prebuiltType)) { BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else { RECEIPT_FIELDS.forEach(receiptField -> { final Map<String, FormField> actualRecognizedReceiptFields = actualForm.getFields(); Map<String, FieldValue> expectedReceiptFields = rawDocumentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(rawDocumentResult.getFields().get(receiptField), actualRecognizedReceiptFields.get(receiptField), rawReadResults, includeFieldElements); }); } } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNull(formField.getLabelData()); }); }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } void validateNetworkCallRecord(String requestParam, String value) { final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> true); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); URL url = null; try { url = new URL(networkCallRecord.getUri()); } catch (MalformedURLException e) { assertFalse(false, e.getMessage()); } Pattern.compile("&").splitAsStream(url.getQuery()) .map(s -> Arrays.copyOf(s.split("="), 2)) .map(o -> new AbstractMap.SimpleEntry<String, String>(o[0], o[1] == null ? "" : o[1])) .map(entry -> { if (entry.getKey().equals(requestParam)) { assertEquals(value, entry.getValue()); return true; } else { return false; } }); } }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String MULTIPAGE_BUSINESS_CARD_PDF = "business-card-multipage.pdf"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final List<String> BUSINESS_CARD_FIELDS = Arrays.asList("ContactNames", "JobTitles", "Departments", "Emails", "Websites", "MobilePhones", "OtherPhones", "Faxes", "Addresses", "CompanyNames"); static final List<String> RECEIPT_FIELDS = Arrays.asList("MerchantName", "MerchantPhoneNumber", "MerchantAddress", "Total", "Subtotal", "Tax", "TransactionDate", "TransactionDate", "TransactionTime", "Items"); enum PREBUILT_TYPE { RECEIPT, BUSINESS_CARD } Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validatePrebuiltResultData(List<RecognizedForm> actualPrebuiltRecognizedForms, boolean includeFieldElements, PREBUILT_TYPE prebuiltType) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); final List<ReadResult> rawReadResults = rawResponse.getReadResults(); for (int i = 0; i < actualPrebuiltRecognizedForms.size(); i++) { final RecognizedForm actualForm = actualPrebuiltRecognizedForms.get(i); final DocumentResult rawDocumentResult = rawResponse.getDocumentResults().get(i); validateLabeledData(actualForm, includeFieldElements, rawReadResults, rawDocumentResult); if (BUSINESS_CARD.equals(prebuiltType)) { BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else { RECEIPT_FIELDS.forEach(receiptField -> { final Map<String, FormField> actualRecognizedReceiptFields = actualForm.getFields(); Map<String, FieldValue> expectedReceiptFields = rawDocumentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(rawDocumentResult.getFields().get(receiptField), actualRecognizedReceiptFields.get(receiptField), rawReadResults, includeFieldElements); }); } } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNull(formField.getLabelData()); }); }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } void validateNetworkCallRecord(String requestParam, String value) { final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> true); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); URL url = null; try { url = new URL(networkCallRecord.getUri()); } catch (MalformedURLException e) { assertFalse(false, e.getMessage()); } Pattern.compile("&").splitAsStream(url.getQuery()) .map(s -> Arrays.copyOf(s.split("="), 2)) .map(o -> new AbstractMap.SimpleEntry<String, String>(o[0], o[1] == null ? "" : o[1])) .map(entry -> { if (entry.getKey().equals(requestParam)) { assertEquals(value, entry.getValue()); return true; } else { return false; } }); } }
I don't have the contact name page number changes in yet, but yes will check here once I do.
static void validateMultipageBusinessData(List<RecognizedForm> recognizedBusinessCards) { assertEquals(2, recognizedBusinessCards.size()); RecognizedForm businessCard1 = recognizedBusinessCards.get(0); RecognizedForm businessCard2 = recognizedBusinessCards.get(1); assertEquals(1, businessCard1.getPageRange().getFirstPageNumber()); assertEquals(1, businessCard1.getPageRange().getLastPageNumber()); Map<String, FormField> businessCard1Fields = businessCard1.getFields(); List<FormField> emailList = businessCard1Fields.get("Emails").getValue().asList(); assertEquals("johnsinger@contoso.com", emailList.get(0).getValue().asString()); List<FormField> phoneNumberList = businessCard1Fields.get("OtherPhones").getValue().asList(); assertEquals("+14257793479", phoneNumberList.get(0).getValue().asPhoneNumber()); assertNotNull(businessCard1.getPages()); assertEquals(2, businessCard2.getPageRange().getFirstPageNumber()); assertEquals(2, businessCard2.getPageRange().getLastPageNumber()); Map<String, FormField> businessCard2Fields = businessCard2.getFields(); List<FormField> email2List = businessCard2Fields.get("Emails").getValue().asList(); assertEquals("avery.smith@contoso.com", email2List.get(0).getValue().asString()); List<FormField> phoneNumber2List = businessCard2Fields.get("OtherPhones").getValue().asList(); assertEquals("+44 (0) 20 9876 5432", phoneNumber2List.get(0).getValueData().getText()); assertNotNull(businessCard2.getPages()); }
Map<String, FormField> businessCard2Fields = businessCard2.getFields();
static void validateMultipageBusinessData(List<RecognizedForm> recognizedBusinessCards) { assertEquals(2, recognizedBusinessCards.size()); RecognizedForm businessCard1 = recognizedBusinessCards.get(0); RecognizedForm businessCard2 = recognizedBusinessCards.get(1); assertEquals(1, businessCard1.getPageRange().getFirstPageNumber()); assertEquals(1, businessCard1.getPageRange().getLastPageNumber()); Map<String, FormField> businessCard1Fields = businessCard1.getFields(); List<FormField> emailList = businessCard1Fields.get("Emails").getValue().asList(); assertEquals("johnsinger@contoso.com", emailList.get(0).getValue().asString()); List<FormField> phoneNumberList = businessCard1Fields.get("OtherPhones").getValue().asList(); assertEquals("+14257793479", phoneNumberList.get(0).getValue().asPhoneNumber()); assertNotNull(businessCard1.getPages()); assertEquals(2, businessCard2.getPageRange().getFirstPageNumber()); assertEquals(2, businessCard2.getPageRange().getLastPageNumber()); Map<String, FormField> businessCard2Fields = businessCard2.getFields(); List<FormField> email2List = businessCard2Fields.get("Emails").getValue().asList(); assertEquals("avery.smith@contoso.com", email2List.get(0).getValue().asString()); List<FormField> phoneNumber2List = businessCard2Fields.get("OtherPhones").getValue().asList(); assertEquals("+44 (0) 20 9876 5432", phoneNumber2List.get(0).getValueData().getText()); assertNotNull(businessCard2.getPages()); }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String MULTIPAGE_BUSINESS_CARD_PDF = "business-card-multipage.pdf"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final List<String> BUSINESS_CARD_FIELDS = Arrays.asList("ContactNames", "JobTitles", "Departments", "Emails", "Websites", "MobilePhones", "OtherPhones", "Faxes", "Addresses", "CompanyNames"); static final List<String> RECEIPT_FIELDS = Arrays.asList("MerchantName", "MerchantPhoneNumber", "MerchantAddress", "Total", "Subtotal", "Tax", "TransactionDate", "TransactionDate", "TransactionTime", "Items"); enum PREBUILT_TYPE { RECEIPT, BUSINESS_CARD } Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validatePrebuiltResultData(List<RecognizedForm> actualPrebuiltRecognizedForms, boolean includeFieldElements, PREBUILT_TYPE prebuiltType) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); final List<ReadResult> rawReadResults = rawResponse.getReadResults(); for (int i = 0; i < actualPrebuiltRecognizedForms.size(); i++) { final RecognizedForm actualForm = actualPrebuiltRecognizedForms.get(i); final DocumentResult rawDocumentResult = rawResponse.getDocumentResults().get(i); validateLabeledData(actualForm, includeFieldElements, rawReadResults, rawDocumentResult); if (BUSINESS_CARD.equals(prebuiltType)) { BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else { RECEIPT_FIELDS.forEach(receiptField -> { final Map<String, FormField> actualRecognizedReceiptFields = actualForm.getFields(); Map<String, FieldValue> expectedReceiptFields = rawDocumentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(rawDocumentResult.getFields().get(receiptField), actualRecognizedReceiptFields.get(receiptField), rawReadResults, includeFieldElements); }); } } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNull(formField.getLabelData()); }); }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } void validateNetworkCallRecord(String requestParam, String value) { final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> true); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); URL url = null; try { url = new URL(networkCallRecord.getUri()); } catch (MalformedURLException e) { assertFalse(false, e.getMessage()); } Pattern.compile("&").splitAsStream(url.getQuery()) .map(s -> Arrays.copyOf(s.split("="), 2)) .map(o -> new AbstractMap.SimpleEntry<String, String>(o[0], o[1] == null ? "" : o[1])) .map(entry -> { if (entry.getKey().equals(requestParam)) { assertEquals(value, entry.getValue()); return true; } else { return false; } }); } }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String MULTIPAGE_BUSINESS_CARD_PDF = "business-card-multipage.pdf"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final List<String> BUSINESS_CARD_FIELDS = Arrays.asList("ContactNames", "JobTitles", "Departments", "Emails", "Websites", "MobilePhones", "OtherPhones", "Faxes", "Addresses", "CompanyNames"); static final List<String> RECEIPT_FIELDS = Arrays.asList("MerchantName", "MerchantPhoneNumber", "MerchantAddress", "Total", "Subtotal", "Tax", "TransactionDate", "TransactionDate", "TransactionTime", "Items"); enum PREBUILT_TYPE { RECEIPT, BUSINESS_CARD } Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validatePrebuiltResultData(List<RecognizedForm> actualPrebuiltRecognizedForms, boolean includeFieldElements, PREBUILT_TYPE prebuiltType) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); final List<ReadResult> rawReadResults = rawResponse.getReadResults(); for (int i = 0; i < actualPrebuiltRecognizedForms.size(); i++) { final RecognizedForm actualForm = actualPrebuiltRecognizedForms.get(i); final DocumentResult rawDocumentResult = rawResponse.getDocumentResults().get(i); validateLabeledData(actualForm, includeFieldElements, rawReadResults, rawDocumentResult); if (BUSINESS_CARD.equals(prebuiltType)) { BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else { RECEIPT_FIELDS.forEach(receiptField -> { final Map<String, FormField> actualRecognizedReceiptFields = actualForm.getFields(); Map<String, FieldValue> expectedReceiptFields = rawDocumentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(rawDocumentResult.getFields().get(receiptField), actualRecognizedReceiptFields.get(receiptField), rawReadResults, includeFieldElements); }); } } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNull(formField.getLabelData()); }); }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } void validateNetworkCallRecord(String requestParam, String value) { final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> true); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); URL url = null; try { url = new URL(networkCallRecord.getUri()); } catch (MalformedURLException e) { assertFalse(false, e.getMessage()); } Pattern.compile("&").splitAsStream(url.getQuery()) .map(s -> Arrays.copyOf(s.split("="), 2)) .map(o -> new AbstractMap.SimpleEntry<String, String>(o[0], o[1] == null ? "" : o[1])) .map(entry -> { if (entry.getKey().equals(requestParam)) { assertEquals(value, entry.getValue()); return true; } else { return false; } }); } }
python/.net are using `isComposedModel`
static CustomFormModel toCustomFormModel(Model modelResponse) { ModelInfo modelInfo = modelResponse.getModelInfo(); if (modelInfo.getStatus() == ModelStatus.INVALID) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format("Model Id %s returned with invalid status.", modelInfo.getModelId()))); } List<TrainingDocumentInfo> trainingDocumentInfoList = null; List<FormRecognizerError> modelErrors = null; final String modelId = modelInfo.getModelId().toString(); if (modelResponse.getTrainResult() != null) { trainingDocumentInfoList = getTrainingDocumentList(modelResponse.getTrainResult().getTrainingDocuments(), modelId); modelErrors = transformTrainingErrors(modelResponse.getTrainResult().getErrors()); } List<CustomFormSubmodel> subModelList = null; if (modelResponse.getKeys() != null) { subModelList = getUnlabeledSubmodels(modelResponse.getKeys().getClusters(), modelId); } else if (modelResponse.getTrainResult() != null && modelResponse.getTrainResult().getFields() != null) { String formType = "custom:"; if (modelInfo.getModelName() != null) { formType = formType + modelInfo.getModelName(); } else { formType = formType + modelInfo.getModelId(); } subModelList = getLabeledSubmodels(modelResponse, modelId, formType); } else if (!CoreUtils.isNullOrEmpty(modelResponse.getComposedTrainResults())) { subModelList = getComposedSubmodels(modelResponse); trainingDocumentInfoList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { final List<TrainingDocumentInfo> trainingDocumentSubModelList = getTrainingDocumentList(composedTrainResultItem.getTrainingDocuments(), composedTrainResultItem.getModelId().toString()); trainingDocumentInfoList.addAll(trainingDocumentSubModelList); } } CustomFormModel customFormModel = new CustomFormModel( modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime(), subModelList, modelErrors, trainingDocumentInfoList); CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); if (modelInfo.getAttributes() != null) { PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); if (modelInfo.getAttributes().isComposed()) { PrivateFieldAccessHelper.set(customFormModel, "trainingDocuments", trainingDocumentInfoList); } } else { PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", false); PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModel, "modelName", modelInfo.getModelName()); } return customFormModel; }
PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", false);
static CustomFormModel toCustomFormModel(Model modelResponse) { ModelInfo modelInfo = modelResponse.getModelInfo(); if (modelInfo.getStatus() == ModelStatus.INVALID) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format("Model Id %s returned with invalid status.", modelInfo.getModelId()))); } List<TrainingDocumentInfo> trainingDocumentInfoList = null; List<FormRecognizerError> modelErrors = null; final String modelId = modelInfo.getModelId().toString(); if (modelResponse.getTrainResult() != null) { trainingDocumentInfoList = getTrainingDocumentList(modelResponse.getTrainResult().getTrainingDocuments(), modelId); modelErrors = transformTrainingErrors(modelResponse.getTrainResult().getErrors()); } List<CustomFormSubmodel> subModelList = null; if (modelResponse.getKeys() != null) { subModelList = getUnlabeledSubmodels(modelResponse.getKeys().getClusters(), modelId); } else if (modelResponse.getTrainResult() != null && modelResponse.getTrainResult().getFields() != null) { String formType = "custom:"; if (modelInfo.getModelName() != null) { formType = formType + modelInfo.getModelName(); } else { formType = formType + modelInfo.getModelId(); } subModelList = getLabeledSubmodels(modelResponse, modelId, formType); } else if (!CoreUtils.isNullOrEmpty(modelResponse.getComposedTrainResults())) { subModelList = getComposedSubmodels(modelResponse); trainingDocumentInfoList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { final List<TrainingDocumentInfo> trainingDocumentSubModelList = getTrainingDocumentList(composedTrainResultItem.getTrainingDocuments(), composedTrainResultItem.getModelId().toString()); trainingDocumentInfoList.addAll(trainingDocumentSubModelList); } } CustomFormModel customFormModel = new CustomFormModel( modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime(), subModelList, modelErrors, trainingDocumentInfoList); CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); if (modelInfo.getAttributes() != null) { PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); if (modelInfo.getAttributes().isComposed()) { PrivateFieldAccessHelper.set(customFormModel, "trainingDocuments", trainingDocumentInfoList); } } else { PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModel, "modelName", modelInfo.getModelName()); } return customFormModel; }
class CustomModelTransforms { private static final ClientLogger LOGGER = new ClientLogger(CustomModelTransforms.class); static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); private CustomModelTransforms() { } /** * Helper method to convert the {@link Model model Response} from service to {@link CustomFormModel}. * * @param modelResponse The {@code Model model response} returned from the service. * * @return The {@link CustomFormModel}. */ /** Creates a training documents info list from service training documents **/ private static List<TrainingDocumentInfo> getTrainingDocumentList( List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> trainingDocuments, String modelId) { return trainingDocuments.stream() .map(trainingDocumentItem -> new TrainingDocumentInfo(trainingDocumentItem.getDocumentName(), TrainingStatus.fromString(trainingDocumentItem.getStatus().toString()), trainingDocumentItem.getPages(), transformTrainingErrors(trainingDocumentItem.getErrors()))) .peek(trainingDocumentInfo -> PrivateFieldAccessHelper.set(trainingDocumentInfo, "modelId", modelId)) .collect(Collectors.toList()); } /** Creates a submodel list from labeled models service data **/ private static List<CustomFormSubmodel> getLabeledSubmodels(Model modelResponse, String modelId, String formType) { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponse.getTrainResult().getFields() .forEach(formFieldsReport -> fieldMap.put(formFieldsReport.getFieldName(), new CustomFormModelField(null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( modelResponse.getTrainResult().getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); return subModelList; } /** Creates a submodel list from unlabeled models service data **/ private static List<CustomFormSubmodel> getUnlabeledSubmodels(Map<String, List<String>> modelResponseClusters, String modelId) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponseClusters .forEach((clusterKey, clusterFields) -> { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); forEachWithIndex(clusterFields, (index, eachField) -> { String fieldName = "field-" + index; fieldMap.put(fieldName, new CustomFormModelField(eachField, fieldName, null)); }); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( null, fieldMap, "form-" + clusterKey); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); }); return subModelList; } /** Creates a submodel list from composed models service data **/ private static List<CustomFormSubmodel> getComposedSubmodels(Model modelResponse) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { String formType = "custom:" + composedTrainResultItem.getModelId().toString(); Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); composedTrainResultItem.getFields() .forEach(formFieldsReport -> fieldMap.put( formFieldsReport.getFieldName(), new CustomFormModelField( null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( composedTrainResultItem.getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", composedTrainResultItem.getModelId().toString()); subModelList.add(customFormSubmodel); } return subModelList; } /** * Transform a list of {@link ModelInfo} to a list of {@link CustomFormModelInfo}. * * @param modelInfoList A list of {@link ModelInfo}. * * @return A list of {@link CustomFormModelInfo}. */ static List<CustomFormModelInfo> toCustomFormModelInfo(List<ModelInfo> modelInfoList) { return modelInfoList.stream() .map(modelInfo -> { CustomFormModelInfo customFormModelInfo = new CustomFormModelInfo(modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime()); if (modelInfo.getAttributes() != null) { CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModelInfo, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModelInfo, "modelName", modelInfo.getModelName()); } return customFormModelInfo; }).collect(Collectors.toList()); } /** * Helper method to convert the list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation} * to list of {@link FormRecognizerError}. * * @param trainingErrorList The list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation}. * * @return The list of {@link FormRecognizerError} */ private static List<FormRecognizerError> transformTrainingErrors( List<com.azure.ai.formrecognizer.implementation.models.ErrorInformation> trainingErrorList) { if (CoreUtils.isNullOrEmpty(trainingErrorList)) { return Collections.emptyList(); } else { return trainingErrorList.stream() .map(errorInformation -> new FormRecognizerError(errorInformation.getCode(), errorInformation.getMessage())) .collect(Collectors.toList()); } } }
class CustomModelTransforms { private static final ClientLogger LOGGER = new ClientLogger(CustomModelTransforms.class); static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); private CustomModelTransforms() { } /** * Helper method to convert the {@link Model model Response} from service to {@link CustomFormModel}. * * @param modelResponse The {@code Model model response} returned from the service. * * @return The {@link CustomFormModel}. */ /** Creates a training documents info list from service training documents **/ private static List<TrainingDocumentInfo> getTrainingDocumentList( List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> trainingDocuments, String modelId) { return trainingDocuments.stream() .map(trainingDocumentItem -> new TrainingDocumentInfo(trainingDocumentItem.getDocumentName(), TrainingStatus.fromString(trainingDocumentItem.getStatus().toString()), trainingDocumentItem.getPages(), transformTrainingErrors(trainingDocumentItem.getErrors()))) .peek(trainingDocumentInfo -> PrivateFieldAccessHelper.set(trainingDocumentInfo, "modelId", modelId)) .collect(Collectors.toList()); } /** Creates a submodel list from labeled models service data **/ private static List<CustomFormSubmodel> getLabeledSubmodels(Model modelResponse, String modelId, String formType) { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponse.getTrainResult().getFields() .forEach(formFieldsReport -> fieldMap.put(formFieldsReport.getFieldName(), new CustomFormModelField(null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( modelResponse.getTrainResult().getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); return subModelList; } /** Creates a submodel list from unlabeled models service data **/ private static List<CustomFormSubmodel> getUnlabeledSubmodels(Map<String, List<String>> modelResponseClusters, String modelId) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponseClusters .forEach((clusterKey, clusterFields) -> { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); forEachWithIndex(clusterFields, (index, eachField) -> { String fieldName = "field-" + index; fieldMap.put(fieldName, new CustomFormModelField(eachField, fieldName, null)); }); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( null, fieldMap, "form-" + clusterKey); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); }); return subModelList; } /** Creates a submodel list from composed models service data **/ private static List<CustomFormSubmodel> getComposedSubmodels(Model modelResponse) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { String formType = "custom:" + composedTrainResultItem.getModelId().toString(); Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); composedTrainResultItem.getFields() .forEach(formFieldsReport -> fieldMap.put( formFieldsReport.getFieldName(), new CustomFormModelField( null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( composedTrainResultItem.getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", composedTrainResultItem.getModelId().toString()); subModelList.add(customFormSubmodel); } return subModelList; } /** * Transform a list of {@link ModelInfo} to a list of {@link CustomFormModelInfo}. * * @param modelInfoList A list of {@link ModelInfo}. * * @return A list of {@link CustomFormModelInfo}. */ static List<CustomFormModelInfo> toCustomFormModelInfo(List<ModelInfo> modelInfoList) { return modelInfoList.stream() .map(modelInfo -> { CustomFormModelInfo customFormModelInfo = new CustomFormModelInfo(modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime()); if (modelInfo.getAttributes() != null) { CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModelInfo, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModelInfo, "modelName", modelInfo.getModelName()); } return customFormModelInfo; }).collect(Collectors.toList()); } /** * Helper method to convert the list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation} * to list of {@link FormRecognizerError}. * * @param trainingErrorList The list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation}. * * @return The list of {@link FormRecognizerError} */ private static List<FormRecognizerError> transformTrainingErrors( List<com.azure.ai.formrecognizer.implementation.models.ErrorInformation> trainingErrorList) { if (CoreUtils.isNullOrEmpty(trainingErrorList)) { return Collections.emptyList(); } else { return trainingErrorList.stream() .map(errorInformation -> new FormRecognizerError(errorInformation.getCode(), errorInformation.getMessage())) .collect(Collectors.toList()); } } }
The default value of java's primitive type, boolean, is false already.
static CustomFormModel toCustomFormModel(Model modelResponse) { ModelInfo modelInfo = modelResponse.getModelInfo(); if (modelInfo.getStatus() == ModelStatus.INVALID) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format("Model Id %s returned with invalid status.", modelInfo.getModelId()))); } List<TrainingDocumentInfo> trainingDocumentInfoList = null; List<FormRecognizerError> modelErrors = null; final String modelId = modelInfo.getModelId().toString(); if (modelResponse.getTrainResult() != null) { trainingDocumentInfoList = getTrainingDocumentList(modelResponse.getTrainResult().getTrainingDocuments(), modelId); modelErrors = transformTrainingErrors(modelResponse.getTrainResult().getErrors()); } List<CustomFormSubmodel> subModelList = null; if (modelResponse.getKeys() != null) { subModelList = getUnlabeledSubmodels(modelResponse.getKeys().getClusters(), modelId); } else if (modelResponse.getTrainResult() != null && modelResponse.getTrainResult().getFields() != null) { String formType = "custom:"; if (modelInfo.getModelName() != null) { formType = formType + modelInfo.getModelName(); } else { formType = formType + modelInfo.getModelId(); } subModelList = getLabeledSubmodels(modelResponse, modelId, formType); } else if (!CoreUtils.isNullOrEmpty(modelResponse.getComposedTrainResults())) { subModelList = getComposedSubmodels(modelResponse); trainingDocumentInfoList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { final List<TrainingDocumentInfo> trainingDocumentSubModelList = getTrainingDocumentList(composedTrainResultItem.getTrainingDocuments(), composedTrainResultItem.getModelId().toString()); trainingDocumentInfoList.addAll(trainingDocumentSubModelList); } } CustomFormModel customFormModel = new CustomFormModel( modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime(), subModelList, modelErrors, trainingDocumentInfoList); CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); if (modelInfo.getAttributes() != null) { PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); if (modelInfo.getAttributes().isComposed()) { PrivateFieldAccessHelper.set(customFormModel, "trainingDocuments", trainingDocumentInfoList); } } else { PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", false); PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModel, "modelName", modelInfo.getModelName()); } return customFormModel; }
PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", false);
static CustomFormModel toCustomFormModel(Model modelResponse) { ModelInfo modelInfo = modelResponse.getModelInfo(); if (modelInfo.getStatus() == ModelStatus.INVALID) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format("Model Id %s returned with invalid status.", modelInfo.getModelId()))); } List<TrainingDocumentInfo> trainingDocumentInfoList = null; List<FormRecognizerError> modelErrors = null; final String modelId = modelInfo.getModelId().toString(); if (modelResponse.getTrainResult() != null) { trainingDocumentInfoList = getTrainingDocumentList(modelResponse.getTrainResult().getTrainingDocuments(), modelId); modelErrors = transformTrainingErrors(modelResponse.getTrainResult().getErrors()); } List<CustomFormSubmodel> subModelList = null; if (modelResponse.getKeys() != null) { subModelList = getUnlabeledSubmodels(modelResponse.getKeys().getClusters(), modelId); } else if (modelResponse.getTrainResult() != null && modelResponse.getTrainResult().getFields() != null) { String formType = "custom:"; if (modelInfo.getModelName() != null) { formType = formType + modelInfo.getModelName(); } else { formType = formType + modelInfo.getModelId(); } subModelList = getLabeledSubmodels(modelResponse, modelId, formType); } else if (!CoreUtils.isNullOrEmpty(modelResponse.getComposedTrainResults())) { subModelList = getComposedSubmodels(modelResponse); trainingDocumentInfoList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { final List<TrainingDocumentInfo> trainingDocumentSubModelList = getTrainingDocumentList(composedTrainResultItem.getTrainingDocuments(), composedTrainResultItem.getModelId().toString()); trainingDocumentInfoList.addAll(trainingDocumentSubModelList); } } CustomFormModel customFormModel = new CustomFormModel( modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime(), subModelList, modelErrors, trainingDocumentInfoList); CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); if (modelInfo.getAttributes() != null) { PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); if (modelInfo.getAttributes().isComposed()) { PrivateFieldAccessHelper.set(customFormModel, "trainingDocuments", trainingDocumentInfoList); } } else { PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModel, "modelName", modelInfo.getModelName()); } return customFormModel; }
class CustomModelTransforms { private static final ClientLogger LOGGER = new ClientLogger(CustomModelTransforms.class); static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); private CustomModelTransforms() { } /** * Helper method to convert the {@link Model model Response} from service to {@link CustomFormModel}. * * @param modelResponse The {@code Model model response} returned from the service. * * @return The {@link CustomFormModel}. */ /** Creates a training documents info list from service training documents **/ private static List<TrainingDocumentInfo> getTrainingDocumentList( List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> trainingDocuments, String modelId) { return trainingDocuments.stream() .map(trainingDocumentItem -> new TrainingDocumentInfo(trainingDocumentItem.getDocumentName(), TrainingStatus.fromString(trainingDocumentItem.getStatus().toString()), trainingDocumentItem.getPages(), transformTrainingErrors(trainingDocumentItem.getErrors()))) .peek(trainingDocumentInfo -> PrivateFieldAccessHelper.set(trainingDocumentInfo, "modelId", modelId)) .collect(Collectors.toList()); } /** Creates a submodel list from labeled models service data **/ private static List<CustomFormSubmodel> getLabeledSubmodels(Model modelResponse, String modelId, String formType) { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponse.getTrainResult().getFields() .forEach(formFieldsReport -> fieldMap.put(formFieldsReport.getFieldName(), new CustomFormModelField(null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( modelResponse.getTrainResult().getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); return subModelList; } /** Creates a submodel list from unlabeled models service data **/ private static List<CustomFormSubmodel> getUnlabeledSubmodels(Map<String, List<String>> modelResponseClusters, String modelId) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponseClusters .forEach((clusterKey, clusterFields) -> { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); forEachWithIndex(clusterFields, (index, eachField) -> { String fieldName = "field-" + index; fieldMap.put(fieldName, new CustomFormModelField(eachField, fieldName, null)); }); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( null, fieldMap, "form-" + clusterKey); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); }); return subModelList; } /** Creates a submodel list from composed models service data **/ private static List<CustomFormSubmodel> getComposedSubmodels(Model modelResponse) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { String formType = "custom:" + composedTrainResultItem.getModelId().toString(); Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); composedTrainResultItem.getFields() .forEach(formFieldsReport -> fieldMap.put( formFieldsReport.getFieldName(), new CustomFormModelField( null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( composedTrainResultItem.getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", composedTrainResultItem.getModelId().toString()); subModelList.add(customFormSubmodel); } return subModelList; } /** * Transform a list of {@link ModelInfo} to a list of {@link CustomFormModelInfo}. * * @param modelInfoList A list of {@link ModelInfo}. * * @return A list of {@link CustomFormModelInfo}. */ static List<CustomFormModelInfo> toCustomFormModelInfo(List<ModelInfo> modelInfoList) { return modelInfoList.stream() .map(modelInfo -> { CustomFormModelInfo customFormModelInfo = new CustomFormModelInfo(modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime()); if (modelInfo.getAttributes() != null) { CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModelInfo, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModelInfo, "modelName", modelInfo.getModelName()); } return customFormModelInfo; }).collect(Collectors.toList()); } /** * Helper method to convert the list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation} * to list of {@link FormRecognizerError}. * * @param trainingErrorList The list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation}. * * @return The list of {@link FormRecognizerError} */ private static List<FormRecognizerError> transformTrainingErrors( List<com.azure.ai.formrecognizer.implementation.models.ErrorInformation> trainingErrorList) { if (CoreUtils.isNullOrEmpty(trainingErrorList)) { return Collections.emptyList(); } else { return trainingErrorList.stream() .map(errorInformation -> new FormRecognizerError(errorInformation.getCode(), errorInformation.getMessage())) .collect(Collectors.toList()); } } }
class CustomModelTransforms { private static final ClientLogger LOGGER = new ClientLogger(CustomModelTransforms.class); static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); private CustomModelTransforms() { } /** * Helper method to convert the {@link Model model Response} from service to {@link CustomFormModel}. * * @param modelResponse The {@code Model model response} returned from the service. * * @return The {@link CustomFormModel}. */ /** Creates a training documents info list from service training documents **/ private static List<TrainingDocumentInfo> getTrainingDocumentList( List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> trainingDocuments, String modelId) { return trainingDocuments.stream() .map(trainingDocumentItem -> new TrainingDocumentInfo(trainingDocumentItem.getDocumentName(), TrainingStatus.fromString(trainingDocumentItem.getStatus().toString()), trainingDocumentItem.getPages(), transformTrainingErrors(trainingDocumentItem.getErrors()))) .peek(trainingDocumentInfo -> PrivateFieldAccessHelper.set(trainingDocumentInfo, "modelId", modelId)) .collect(Collectors.toList()); } /** Creates a submodel list from labeled models service data **/ private static List<CustomFormSubmodel> getLabeledSubmodels(Model modelResponse, String modelId, String formType) { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponse.getTrainResult().getFields() .forEach(formFieldsReport -> fieldMap.put(formFieldsReport.getFieldName(), new CustomFormModelField(null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( modelResponse.getTrainResult().getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); return subModelList; } /** Creates a submodel list from unlabeled models service data **/ private static List<CustomFormSubmodel> getUnlabeledSubmodels(Map<String, List<String>> modelResponseClusters, String modelId) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponseClusters .forEach((clusterKey, clusterFields) -> { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); forEachWithIndex(clusterFields, (index, eachField) -> { String fieldName = "field-" + index; fieldMap.put(fieldName, new CustomFormModelField(eachField, fieldName, null)); }); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( null, fieldMap, "form-" + clusterKey); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); }); return subModelList; } /** Creates a submodel list from composed models service data **/ private static List<CustomFormSubmodel> getComposedSubmodels(Model modelResponse) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { String formType = "custom:" + composedTrainResultItem.getModelId().toString(); Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); composedTrainResultItem.getFields() .forEach(formFieldsReport -> fieldMap.put( formFieldsReport.getFieldName(), new CustomFormModelField( null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( composedTrainResultItem.getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", composedTrainResultItem.getModelId().toString()); subModelList.add(customFormSubmodel); } return subModelList; } /** * Transform a list of {@link ModelInfo} to a list of {@link CustomFormModelInfo}. * * @param modelInfoList A list of {@link ModelInfo}. * * @return A list of {@link CustomFormModelInfo}. */ static List<CustomFormModelInfo> toCustomFormModelInfo(List<ModelInfo> modelInfoList) { return modelInfoList.stream() .map(modelInfo -> { CustomFormModelInfo customFormModelInfo = new CustomFormModelInfo(modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime()); if (modelInfo.getAttributes() != null) { CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModelInfo, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModelInfo, "modelName", modelInfo.getModelName()); } return customFormModelInfo; }).collect(Collectors.toList()); } /** * Helper method to convert the list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation} * to list of {@link FormRecognizerError}. * * @param trainingErrorList The list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation}. * * @return The list of {@link FormRecognizerError} */ private static List<FormRecognizerError> transformTrainingErrors( List<com.azure.ai.formrecognizer.implementation.models.ErrorInformation> trainingErrorList) { if (CoreUtils.isNullOrEmpty(trainingErrorList)) { return Collections.emptyList(); } else { return trainingErrorList.stream() .map(errorInformation -> new FormRecognizerError(errorInformation.getCode(), errorInformation.getMessage())) .collect(Collectors.toList()); } } }
But we weren't setting `customModelProperties` so doing that too :)
static CustomFormModel toCustomFormModel(Model modelResponse) { ModelInfo modelInfo = modelResponse.getModelInfo(); if (modelInfo.getStatus() == ModelStatus.INVALID) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format("Model Id %s returned with invalid status.", modelInfo.getModelId()))); } List<TrainingDocumentInfo> trainingDocumentInfoList = null; List<FormRecognizerError> modelErrors = null; final String modelId = modelInfo.getModelId().toString(); if (modelResponse.getTrainResult() != null) { trainingDocumentInfoList = getTrainingDocumentList(modelResponse.getTrainResult().getTrainingDocuments(), modelId); modelErrors = transformTrainingErrors(modelResponse.getTrainResult().getErrors()); } List<CustomFormSubmodel> subModelList = null; if (modelResponse.getKeys() != null) { subModelList = getUnlabeledSubmodels(modelResponse.getKeys().getClusters(), modelId); } else if (modelResponse.getTrainResult() != null && modelResponse.getTrainResult().getFields() != null) { String formType = "custom:"; if (modelInfo.getModelName() != null) { formType = formType + modelInfo.getModelName(); } else { formType = formType + modelInfo.getModelId(); } subModelList = getLabeledSubmodels(modelResponse, modelId, formType); } else if (!CoreUtils.isNullOrEmpty(modelResponse.getComposedTrainResults())) { subModelList = getComposedSubmodels(modelResponse); trainingDocumentInfoList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { final List<TrainingDocumentInfo> trainingDocumentSubModelList = getTrainingDocumentList(composedTrainResultItem.getTrainingDocuments(), composedTrainResultItem.getModelId().toString()); trainingDocumentInfoList.addAll(trainingDocumentSubModelList); } } CustomFormModel customFormModel = new CustomFormModel( modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime(), subModelList, modelErrors, trainingDocumentInfoList); CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); if (modelInfo.getAttributes() != null) { PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); if (modelInfo.getAttributes().isComposed()) { PrivateFieldAccessHelper.set(customFormModel, "trainingDocuments", trainingDocumentInfoList); } } else { PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", false); PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModel, "modelName", modelInfo.getModelName()); } return customFormModel; }
PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", false);
static CustomFormModel toCustomFormModel(Model modelResponse) { ModelInfo modelInfo = modelResponse.getModelInfo(); if (modelInfo.getStatus() == ModelStatus.INVALID) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format("Model Id %s returned with invalid status.", modelInfo.getModelId()))); } List<TrainingDocumentInfo> trainingDocumentInfoList = null; List<FormRecognizerError> modelErrors = null; final String modelId = modelInfo.getModelId().toString(); if (modelResponse.getTrainResult() != null) { trainingDocumentInfoList = getTrainingDocumentList(modelResponse.getTrainResult().getTrainingDocuments(), modelId); modelErrors = transformTrainingErrors(modelResponse.getTrainResult().getErrors()); } List<CustomFormSubmodel> subModelList = null; if (modelResponse.getKeys() != null) { subModelList = getUnlabeledSubmodels(modelResponse.getKeys().getClusters(), modelId); } else if (modelResponse.getTrainResult() != null && modelResponse.getTrainResult().getFields() != null) { String formType = "custom:"; if (modelInfo.getModelName() != null) { formType = formType + modelInfo.getModelName(); } else { formType = formType + modelInfo.getModelId(); } subModelList = getLabeledSubmodels(modelResponse, modelId, formType); } else if (!CoreUtils.isNullOrEmpty(modelResponse.getComposedTrainResults())) { subModelList = getComposedSubmodels(modelResponse); trainingDocumentInfoList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { final List<TrainingDocumentInfo> trainingDocumentSubModelList = getTrainingDocumentList(composedTrainResultItem.getTrainingDocuments(), composedTrainResultItem.getModelId().toString()); trainingDocumentInfoList.addAll(trainingDocumentSubModelList); } } CustomFormModel customFormModel = new CustomFormModel( modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime(), subModelList, modelErrors, trainingDocumentInfoList); CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); if (modelInfo.getAttributes() != null) { PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); if (modelInfo.getAttributes().isComposed()) { PrivateFieldAccessHelper.set(customFormModel, "trainingDocuments", trainingDocumentInfoList); } } else { PrivateFieldAccessHelper.set(customFormModel, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModel, "modelName", modelInfo.getModelName()); } return customFormModel; }
class CustomModelTransforms { private static final ClientLogger LOGGER = new ClientLogger(CustomModelTransforms.class); static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); private CustomModelTransforms() { } /** * Helper method to convert the {@link Model model Response} from service to {@link CustomFormModel}. * * @param modelResponse The {@code Model model response} returned from the service. * * @return The {@link CustomFormModel}. */ /** Creates a training documents info list from service training documents **/ private static List<TrainingDocumentInfo> getTrainingDocumentList( List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> trainingDocuments, String modelId) { return trainingDocuments.stream() .map(trainingDocumentItem -> new TrainingDocumentInfo(trainingDocumentItem.getDocumentName(), TrainingStatus.fromString(trainingDocumentItem.getStatus().toString()), trainingDocumentItem.getPages(), transformTrainingErrors(trainingDocumentItem.getErrors()))) .peek(trainingDocumentInfo -> PrivateFieldAccessHelper.set(trainingDocumentInfo, "modelId", modelId)) .collect(Collectors.toList()); } /** Creates a submodel list from labeled models service data **/ private static List<CustomFormSubmodel> getLabeledSubmodels(Model modelResponse, String modelId, String formType) { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponse.getTrainResult().getFields() .forEach(formFieldsReport -> fieldMap.put(formFieldsReport.getFieldName(), new CustomFormModelField(null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( modelResponse.getTrainResult().getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); return subModelList; } /** Creates a submodel list from unlabeled models service data **/ private static List<CustomFormSubmodel> getUnlabeledSubmodels(Map<String, List<String>> modelResponseClusters, String modelId) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponseClusters .forEach((clusterKey, clusterFields) -> { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); forEachWithIndex(clusterFields, (index, eachField) -> { String fieldName = "field-" + index; fieldMap.put(fieldName, new CustomFormModelField(eachField, fieldName, null)); }); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( null, fieldMap, "form-" + clusterKey); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); }); return subModelList; } /** Creates a submodel list from composed models service data **/ private static List<CustomFormSubmodel> getComposedSubmodels(Model modelResponse) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { String formType = "custom:" + composedTrainResultItem.getModelId().toString(); Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); composedTrainResultItem.getFields() .forEach(formFieldsReport -> fieldMap.put( formFieldsReport.getFieldName(), new CustomFormModelField( null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( composedTrainResultItem.getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", composedTrainResultItem.getModelId().toString()); subModelList.add(customFormSubmodel); } return subModelList; } /** * Transform a list of {@link ModelInfo} to a list of {@link CustomFormModelInfo}. * * @param modelInfoList A list of {@link ModelInfo}. * * @return A list of {@link CustomFormModelInfo}. */ static List<CustomFormModelInfo> toCustomFormModelInfo(List<ModelInfo> modelInfoList) { return modelInfoList.stream() .map(modelInfo -> { CustomFormModelInfo customFormModelInfo = new CustomFormModelInfo(modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime()); if (modelInfo.getAttributes() != null) { CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModelInfo, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModelInfo, "modelName", modelInfo.getModelName()); } return customFormModelInfo; }).collect(Collectors.toList()); } /** * Helper method to convert the list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation} * to list of {@link FormRecognizerError}. * * @param trainingErrorList The list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation}. * * @return The list of {@link FormRecognizerError} */ private static List<FormRecognizerError> transformTrainingErrors( List<com.azure.ai.formrecognizer.implementation.models.ErrorInformation> trainingErrorList) { if (CoreUtils.isNullOrEmpty(trainingErrorList)) { return Collections.emptyList(); } else { return trainingErrorList.stream() .map(errorInformation -> new FormRecognizerError(errorInformation.getCode(), errorInformation.getMessage())) .collect(Collectors.toList()); } } }
class CustomModelTransforms { private static final ClientLogger LOGGER = new ClientLogger(CustomModelTransforms.class); static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); private CustomModelTransforms() { } /** * Helper method to convert the {@link Model model Response} from service to {@link CustomFormModel}. * * @param modelResponse The {@code Model model response} returned from the service. * * @return The {@link CustomFormModel}. */ /** Creates a training documents info list from service training documents **/ private static List<TrainingDocumentInfo> getTrainingDocumentList( List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> trainingDocuments, String modelId) { return trainingDocuments.stream() .map(trainingDocumentItem -> new TrainingDocumentInfo(trainingDocumentItem.getDocumentName(), TrainingStatus.fromString(trainingDocumentItem.getStatus().toString()), trainingDocumentItem.getPages(), transformTrainingErrors(trainingDocumentItem.getErrors()))) .peek(trainingDocumentInfo -> PrivateFieldAccessHelper.set(trainingDocumentInfo, "modelId", modelId)) .collect(Collectors.toList()); } /** Creates a submodel list from labeled models service data **/ private static List<CustomFormSubmodel> getLabeledSubmodels(Model modelResponse, String modelId, String formType) { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponse.getTrainResult().getFields() .forEach(formFieldsReport -> fieldMap.put(formFieldsReport.getFieldName(), new CustomFormModelField(null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( modelResponse.getTrainResult().getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); return subModelList; } /** Creates a submodel list from unlabeled models service data **/ private static List<CustomFormSubmodel> getUnlabeledSubmodels(Map<String, List<String>> modelResponseClusters, String modelId) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); modelResponseClusters .forEach((clusterKey, clusterFields) -> { Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); forEachWithIndex(clusterFields, (index, eachField) -> { String fieldName = "field-" + index; fieldMap.put(fieldName, new CustomFormModelField(eachField, fieldName, null)); }); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( null, fieldMap, "form-" + clusterKey); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", modelId); subModelList.add(customFormSubmodel); }); return subModelList; } /** Creates a submodel list from composed models service data **/ private static List<CustomFormSubmodel> getComposedSubmodels(Model modelResponse) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { String formType = "custom:" + composedTrainResultItem.getModelId().toString(); Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); composedTrainResultItem.getFields() .forEach(formFieldsReport -> fieldMap.put( formFieldsReport.getFieldName(), new CustomFormModelField( null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( composedTrainResultItem.getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", composedTrainResultItem.getModelId().toString()); subModelList.add(customFormSubmodel); } return subModelList; } /** * Transform a list of {@link ModelInfo} to a list of {@link CustomFormModelInfo}. * * @param modelInfoList A list of {@link ModelInfo}. * * @return A list of {@link CustomFormModelInfo}. */ static List<CustomFormModelInfo> toCustomFormModelInfo(List<ModelInfo> modelInfoList) { return modelInfoList.stream() .map(modelInfo -> { CustomFormModelInfo customFormModelInfo = new CustomFormModelInfo(modelInfo.getModelId().toString(), CustomFormModelStatus.fromString(modelInfo.getStatus().toString()), modelInfo.getCreatedDateTime(), modelInfo.getLastUpdatedDateTime()); if (modelInfo.getAttributes() != null) { CustomFormModelProperties customFormModelProperties = new CustomFormModelProperties(); PrivateFieldAccessHelper.set(customFormModelProperties, "isComposed", modelInfo.getAttributes().isComposed()); PrivateFieldAccessHelper.set(customFormModelInfo, "customFormModelProperties", customFormModelProperties); } if (modelInfo.getModelName() != null) { PrivateFieldAccessHelper.set(customFormModelInfo, "modelName", modelInfo.getModelName()); } return customFormModelInfo; }).collect(Collectors.toList()); } /** * Helper method to convert the list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation} * to list of {@link FormRecognizerError}. * * @param trainingErrorList The list of {@link com.azure.ai.formrecognizer.implementation.models.ErrorInformation}. * * @return The list of {@link FormRecognizerError} */ private static List<FormRecognizerError> transformTrainingErrors( List<com.azure.ai.formrecognizer.implementation.models.ErrorInformation> trainingErrorList) { if (CoreUtils.isNullOrEmpty(trainingErrorList)) { return Collections.emptyList(); } else { return trainingErrorList.stream() .map(errorInformation -> new FormRecognizerError(errorInformation.getCode(), errorInformation.getMessage())) .collect(Collectors.toList()); } } }
I prefer the following code: ``` String subscriptionId = Optional.of(azureProperties) .map(AzureProperties::getSubscriptionId) .orElseGet(credentials::defaultSubscriptionId); return Azure.authenticate(restClient, credentials.domain()) .withSubscription(subscriptionId); ```
public Azure azure(AzureTokenCredentials credentials, AzureProperties azureProperties) throws IOException { RestClient restClient = new RestClient.Builder() .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER) .withCredentials(credentials).withSerializerAdapter(new AzureJacksonAdapter()) .withResponseBuilderFactory(new AzureResponseBuilder.Factory()) .withInterceptor(new ProviderRegistrationInterceptor(credentials)) .withInterceptor(new ResourceManagerThrottlingInterceptor()).withUserAgent(SPRING_CLOUD_USER_AGENT) .build(); if (azureProperties.getSubscriptionId() == null) { return Azure.authenticate(restClient, credentials.domain()) .withSubscription(credentials.defaultSubscriptionId()); } else { return Azure.authenticate(restClient, credentials.domain()) .withSubscription(azureProperties.getSubscriptionId()); } }
.withSubscription(azureProperties.getSubscriptionId());
public Azure azure(AzureTokenCredentials credentials, AzureProperties azureProperties) throws IOException { RestClient restClient = new RestClient.Builder() .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER) .withCredentials(credentials).withSerializerAdapter(new AzureJacksonAdapter()) .withResponseBuilderFactory(new AzureResponseBuilder.Factory()) .withInterceptor(new ProviderRegistrationInterceptor(credentials)) .withInterceptor(new ResourceManagerThrottlingInterceptor()).withUserAgent(SPRING_CLOUD_USER_AGENT) .build(); String subscriptionId = Optional.of(azureProperties.getSubscriptionId()) .orElseGet(credentials::defaultSubscriptionId); return Azure.authenticate(restClient, credentials.domain()) .withSubscription(subscriptionId); }
class AzureContextAutoConfiguration { private static final String PROJECT_VERSION = AzureContextAutoConfiguration.class.getPackage().getImplementationVersion(); private static final String SPRING_CLOUD_USER_AGENT = "spring-cloud-azure/" + PROJECT_VERSION; @Bean @ConditionalOnMissingBean public ResourceManagerProvider resourceManagerProvider(Azure azure, AzureProperties azureProperties) { return new AzureResourceManagerProvider(azure, azureProperties); } @Bean @ConditionalOnMissingBean @Bean @ConditionalOnMissingBean public AzureTokenCredentials credentials(AzureProperties azureProperties) { CredentialsProvider credentialsProvider = new DefaultCredentialsProvider(azureProperties); return credentialsProvider.getCredentials(); } }
class AzureContextAutoConfiguration { private static final String PROJECT_VERSION = AzureContextAutoConfiguration.class.getPackage().getImplementationVersion(); private static final String SPRING_CLOUD_USER_AGENT = "spring-cloud-azure/" + PROJECT_VERSION; @Bean @ConditionalOnMissingBean public ResourceManagerProvider resourceManagerProvider(Azure azure, AzureProperties azureProperties) { return new AzureResourceManagerProvider(azure, azureProperties); } @Bean @ConditionalOnMissingBean @Bean @ConditionalOnMissingBean public AzureTokenCredentials credentials(AzureProperties azureProperties) { CredentialsProvider credentialsProvider = new DefaultCredentialsProvider(azureProperties); return credentialsProvider.getCredentials(); } }
When client calls `acceptNextSession` : it should go to service bus and get a lock to any session and if client do not do receiveMessages() on it, the session is locked, no one else can get it. Can you try that ? `getActiveLink()` returns a Mono and until a user subscribe to it, it will not create link.
public Mono<ServiceBusReceiverAsyncClient> acceptNextSession() { return unNamedSessionManager.getActiveLink().flatMap(receiveLink -> receiveLink.getSessionId() .map(sessionId -> { ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), sessionId, null, receiverOptions.getMaxLockRenewDuration()); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions, receiveLink); return new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, onClientClose, sessionSpecificManager); })); }
return unNamedSessionManager.getActiveLink().flatMap(receiveLink -> receiveLink.getSessionId()
public Mono<ServiceBusReceiverAsyncClient> acceptNextSession() { return unNamedSessionManager.getActiveLink().flatMap(receiveLink -> receiveLink.getSessionId() .map(sessionId -> { final ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), receiverOptions.getMaxLockRenewDuration(), receiverOptions.isAutoLockRenewEnabled(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions, receiveLink); return new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager); })); }
class ServiceBusSessionReceiverAsyncClient implements AutoCloseable { private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager unNamedSessionManager; private final ClientLogger logger = new ClientLogger(ServiceBusSessionReceiverAsyncClient.class); ServiceBusSessionReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.unNamedSessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); } /** * Create a link for the next available session and use the link to create a {@link ServiceBusReceiverAsyncClient} * to receive messages from that session. * @return A {@link ServiceBusReceiverAsyncClient} that is tied to the available session. */ /** * Create a link for the "sessionId" and use the link to create a {@link ServiceBusReceiverAsyncClient} * to receive messages from the session. * @param sessionId The session Id. * @return A {@link ServiceBusReceiverAsyncClient} that is tied to the specified session. * @throws IllegalArgumentException if {@code sessionId} is null or empty. */ public Mono<ServiceBusReceiverAsyncClient> acceptSession(String sessionId) { if (CoreUtils.isNullOrEmpty(sessionId)) { return monoError(logger, new IllegalArgumentException("sessionId can not be null or empty")); } ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), sessionId, null, receiverOptions.getMaxLockRenewDuration()); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); return sessionSpecificManager.getActiveLink().thenReturn(new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, onClientClose, sessionSpecificManager)); } /** * Create a {@link ServiceBusReceiverAsyncClient} that processes at most {@code maxConcurrentSessions} sessions. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The {@link ServiceBusReceiverAsyncClient} object that will be used to receive messages. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusReceiverAsyncClient getReceiverClient(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), null, maxConcurrentSessions, receiverOptions.getMaxLockRenewDuration()); ServiceBusSessionManager newSessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); return new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, onClientClose, newSessionManager); } @Override public void close() { this.onClientClose.run(); } }
class ServiceBusSessionReceiverAsyncClient implements AutoCloseable { private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager unNamedSessionManager; private final ClientLogger logger = new ClientLogger(ServiceBusSessionReceiverAsyncClient.class); ServiceBusSessionReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.unNamedSessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); } /** * Acquires a session lock for the next available session and create a {@link ServiceBusReceiverAsyncClient} * to receive messages from the session. It will wait until a session is available if no one is available * immediately. * * {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.instantiation * * @return A {@link ServiceBusReceiverAsyncClient} that is tied to the available session. * @throws UnsupportedOperationException if the queue or topic subscription is not session-enabled. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Acquires a session lock for {@code sessionId} and create a {@link ServiceBusReceiverAsyncClient} * to receive messages from the session. If the session is already locked by another client, an * {@link com.azure.core.amqp.exception.AmqpException} is thrown. * * {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.instantiation * * @param sessionId The session Id. * @return A {@link ServiceBusReceiverAsyncClient} that is tied to the specified session. * @throws NullPointerException if {@code sessionId} is null. * @throws IllegalArgumentException if {@code sessionId} is empty. * @throws UnsupportedOperationException if the queue or topic subscription is not session-enabled. * @throws com.azure.core.amqp.exception.AmqpException if the lock cannot be acquired. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ServiceBusReceiverAsyncClient> acceptSession(String sessionId) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null")); } if (CoreUtils.isNullOrEmpty(sessionId)) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be empty")); } final ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), receiverOptions.getMaxLockRenewDuration(), receiverOptions.isAutoLockRenewEnabled(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); return sessionSpecificManager.getActiveLink().map(receiveLink -> new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager)); } @Override public void close() { this.onClientClose.run(); } }
nit: consistent use of final.
public Mono<ServiceBusReceiverAsyncClient> acceptNextSession() { return unNamedSessionManager.getActiveLink().flatMap(receiveLink -> receiveLink.getSessionId() .map(sessionId -> { ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), sessionId, null, receiverOptions.getMaxLockRenewDuration()); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions, receiveLink); return new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, onClientClose, sessionSpecificManager); })); }
ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(),
public Mono<ServiceBusReceiverAsyncClient> acceptNextSession() { return unNamedSessionManager.getActiveLink().flatMap(receiveLink -> receiveLink.getSessionId() .map(sessionId -> { final ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), receiverOptions.getMaxLockRenewDuration(), receiverOptions.isAutoLockRenewEnabled(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions, receiveLink); return new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager); })); }
class ServiceBusSessionReceiverAsyncClient implements AutoCloseable { private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager unNamedSessionManager; private final ClientLogger logger = new ClientLogger(ServiceBusSessionReceiverAsyncClient.class); ServiceBusSessionReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.unNamedSessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); } /** * Create a link for the next available session and use the link to create a {@link ServiceBusReceiverAsyncClient} * to receive messages from that session. * @return A {@link ServiceBusReceiverAsyncClient} that is tied to the available session. */ /** * Create a link for the "sessionId" and use the link to create a {@link ServiceBusReceiverAsyncClient} * to receive messages from the session. * @param sessionId The session Id. * @return A {@link ServiceBusReceiverAsyncClient} that is tied to the specified session. * @throws IllegalArgumentException if {@code sessionId} is null or empty. */ public Mono<ServiceBusReceiverAsyncClient> acceptSession(String sessionId) { if (CoreUtils.isNullOrEmpty(sessionId)) { return monoError(logger, new IllegalArgumentException("sessionId can not be null or empty")); } ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), sessionId, null, receiverOptions.getMaxLockRenewDuration()); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); return sessionSpecificManager.getActiveLink().thenReturn(new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, onClientClose, sessionSpecificManager)); } /** * Create a {@link ServiceBusReceiverAsyncClient} that processes at most {@code maxConcurrentSessions} sessions. * * @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time. * * @return The {@link ServiceBusReceiverAsyncClient} object that will be used to receive messages. * @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1. */ public ServiceBusReceiverAsyncClient getReceiverClient(int maxConcurrentSessions) { if (maxConcurrentSessions < 1) { throw logger.logExceptionAsError( new IllegalArgumentException("Maximum number of concurrent sessions must be positive.")); } ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), null, maxConcurrentSessions, receiverOptions.getMaxLockRenewDuration()); ServiceBusSessionManager newSessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); return new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, onClientClose, newSessionManager); } @Override public void close() { this.onClientClose.run(); } }
class ServiceBusSessionReceiverAsyncClient implements AutoCloseable { private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager unNamedSessionManager; private final ClientLogger logger = new ClientLogger(ServiceBusSessionReceiverAsyncClient.class); ServiceBusSessionReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.unNamedSessionManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, receiverOptions); } /** * Acquires a session lock for the next available session and create a {@link ServiceBusReceiverAsyncClient} * to receive messages from the session. It will wait until a session is available if no one is available * immediately. * * {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.instantiation * * @return A {@link ServiceBusReceiverAsyncClient} that is tied to the available session. * @throws UnsupportedOperationException if the queue or topic subscription is not session-enabled. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Acquires a session lock for {@code sessionId} and create a {@link ServiceBusReceiverAsyncClient} * to receive messages from the session. If the session is already locked by another client, an * {@link com.azure.core.amqp.exception.AmqpException} is thrown. * * {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.instantiation * * @param sessionId The session Id. * @return A {@link ServiceBusReceiverAsyncClient} that is tied to the specified session. * @throws NullPointerException if {@code sessionId} is null. * @throws IllegalArgumentException if {@code sessionId} is empty. * @throws UnsupportedOperationException if the queue or topic subscription is not session-enabled. * @throws com.azure.core.amqp.exception.AmqpException if the lock cannot be acquired. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ServiceBusReceiverAsyncClient> acceptSession(String sessionId) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null")); } if (CoreUtils.isNullOrEmpty(sessionId)) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be empty")); } final ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), receiverOptions.getMaxLockRenewDuration(), receiverOptions.isAutoLockRenewEnabled(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); return sessionSpecificManager.getActiveLink().map(receiveLink -> new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager)); } @Override public void close() { this.onClientClose.run(); } }